Building a Cookie-Based Session Management System with Spring Boot

A cookie-based session management system with Spring Boot lets a web application remember an authenticated user between requests. The browser stores a short session identifier, while the server keeps the user’s session data in memory or a shared data store.

This approach suits traditional web applications, administration portals, booking systems and customer dashboards. It is different from stateless token authentication, where each request carries all required authentication claims.

For an Australian audience, session design should account for customers using mobile networks in Sydney, Melbourne and regional areas. Reliable cookie handling is especially important when a user moves between Wi-Fi and mobile data during a checkout or account session.

The Privacy Act 1988 and the Australian Privacy Principles (APPs) also influence how session information is collected, stored and protected. A session identifier should not contain unnecessary personal details, and retention should match the application’s privacy policy.

Choosing A Server-Side Session Model

Spring Boot can use the servlet container’s default HttpSession, which is suitable for a single application instance. The browser receives a JSESSIONID cookie, and the server associates that value with session attributes such as a user ID or shopping cart.

For production deployments with multiple application instances, Spring Session provides a shared session repository. JDBC stores sessions in a relational database, while Redis offers fast access and automatic expiry. Shared storage prevents a user from losing their login when a load balancer sends a request to another instance.

Add the relevant dependency to a Maven project:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-jdbc</artifactId>
</dependency>

Spring Boot can initialise the required database schema, or the schema scripts can be managed through a migration tool such as Flyway.

Configuring The Session Cookie

Cookie attributes should be configured deliberately rather than relying on browser defaults. In application.properties, a basic setup may look like this:

server.servlet.session.cookie.name=APP_SESSION
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=lax
server.servlet.session.timeout=30m

HttpOnly prevents JavaScript from reading the cookie, which limits exposure during some cross-site scripting attacks. Secure ensures the cookie travels only over HTTPS. The SameSite setting reduces cross-site request risks while allowing ordinary navigation and login flows.

During local HTTP development, secure=true can prevent the browser from sending the cookie. Use HTTPS locally where practical, or apply environment-specific configuration without weakening the production profile.

Creating And Reading Session Data

A controller can access the current session through HttpSession. Keep the stored value small and non-sensitive, such as an internal account identifier.

@GetMapping("/account")
public String account(HttpSession session, Model model) {
    Long accountId = (Long) session.getAttribute("accountId");

    if (accountId == null) {
        return "redirect:/login";
    }

    model.addAttribute("accountId", accountId);
    return "account";
}

Avoid storing passwords, payment card information or complete customer profiles in session attributes. Australian retailers handling local online payments should leave card processing to a compliant payment provider and store only a provider reference or order status.

Connecting Sessions With Spring Security

Spring Security normally manages the authenticated principal and can use the HTTP session to remember that authentication. A simple security configuration can define which pages require a logged-in user:

@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/", "/login", "/css/**").permitAll()
            .anyRequest().authenticated()
        )
        .formLogin(form -> form.loginPage("/login").permitAll())
        .logout(logout -> logout
            .logoutSuccessUrl("/")
            .invalidateHttpSession(true)
            .deleteCookies("APP_SESSION")
        );

    return http.build();
}

After successful authentication, Spring Security should rotate the session identifier to reduce session fixation risk. Keep this behaviour enabled, and ensure the login process invalidates old authentication state where custom authentication code is used.

A custom login endpoint must validate credentials through a password encoder and should avoid placing an email address or role list directly in a client-controlled cookie.

Protecting Requests Against Common Attacks

Cookie authentication automatically sends credentials with matching requests, so cross-site request forgery (CSRF) needs attention. Spring Security enables CSRF protection by default for browser applications. Thymeleaf forms can include the generated CSRF token automatically when configured correctly.

Useful safeguards include:

Session identifiers should be generated by the framework using strong randomness. Do not create IDs from usernames, timestamps or predictable hashes. Rate-limit login attempts and record security events without logging raw cookie values.

Sharing Sessions Across Multiple Servers

A JDBC-backed session repository is practical when an application already uses PostgreSQL or MySQL. It provides straightforward operational visibility, although database traffic can increase during busy periods. Redis is often preferable for high-volume session reads and short-lived session records.

The infrastructure must use a consistent cookie domain, path and HTTPS policy. A Sydney-based service serving customers throughout Australia may deploy across multiple availability zones, making shared session storage and health checks essential for uninterrupted browsing.

Use an expiry policy that reflects the business process. A banking-style portal may use a short idle timeout, while an online grocery basket may need a longer period. Explain session expiry in the privacy notice and avoid retaining abandoned personal data indefinitely.

Testing And Monitoring Session Behaviour

Test login, logout, expiry, concurrent requests and access from separate browsers. Browser developer tools can confirm whether the cookie has the correct domain, path, expiry, Secure, HttpOnly and SameSite attributes.

Include automated tests for unauthenticated redirects, CSRF failures and session fixation protection. Test deployments behind a reverse proxy as well, because incorrect HTTPS forwarding headers can cause secure cookies to behave unexpectedly.

A production checklist should include:

Comparing Session Storage Approaches

The best storage option depends on traffic, deployment architecture and operational skills. A single-instance internal tool may need no additional infrastructure, while a national customer platform may require a shared and highly available repository.

Approach Suitable For Main Advantage Main Consideration
In-memory HttpSession Local development and one server Simple setup Sessions disappear on restart
JDBC with Spring Session Existing relational database environments Familiar persistence and reporting Database load and schema management
Redis with Spring Session Scaled, high-traffic applications Fast reads and shared sessions Requires Redis operations and availability planning
Stateless tokens APIs and distributed clients No server-side session store Revocation, token leakage and browser security require extra care

Cookie-based sessions remain a practical choice for Spring Boot browser applications when the cookie contains only an unpredictable identifier and the server controls the associated state. With secure attributes, Spring Security integration, shared storage where needed and privacy-aware retention, the design can support Australian customers from first login through logout.