Skip to lesson

Form login and session cookies

ShopLite admins open dozens of pages in a row. Asking for the password on every page would be unbearable, so the server must recognise the same browser after one sign-in. How does it do that without leaving the door open?

formLogin: the login page, POST /login and the redirect

formLogin is the Spring Security setting that signs users in through an HTML form: GET /login shows the form, POST /login checks the email and password, and a redirect (a 302 reply with a Location header) sends the browser on.

A few lines in SecurityConfig switch on the form login. The second example then walks through the whole trip with curl, saving the cookies in a file.

Example 1 · src/main/java/com/shoplite/lab/security/SecurityConfig.java

Runs in: the session-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .requestMatchers("/error").permitAll()                .anyRequest().authenticated())            .formLogin(Customizer.withDefaults())   // GET /login shows a form, POST /login checks it            .logout(Customizer.withDefaults());     // POST /logout ends the session        // CSRF protection and sessions stay at their defaults: ON        return http.build();    }}
Sample output
$ curl -i -c jar.txt http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=B23948098D6037BF84A97A86372E6DF4; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login
Content-Length: 0
Date: Fri, 16 Oct 2026 07:12:59 GMT

$ curl -b jar.txt -c jar.txt http://localhost:8080/login
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Please sign in</title>
    <link href="/default-ui.css" rel="stylesheet" />
  </head>
  <body>
    <div class="content">
      <form class="login-form" method="post" action="/login">
        <h2>Please sign in</h2>

        <p>
          <label for="username" class="screenreader">Username</label>
          <input type="text" id="username" name="username" placeholder="Username" required autofocus>
        </p>
        <p>
          <label for="password" class="screenreader">Password</label>
          <input type="password" id="password" name="password" placeholder="Password" required>
        </p>

<input name="_csrf" type="hidden" value="3nfLVIkSoiUTUylIxVzQBd3yoBek255ZCt395CA_WDS_qeqyv0LyMrBwkRY-ax19pnHkZ-TLjS7G7Kp0aejF1EFaPQ2Mn9nQ" />
        <button type="submit" class="primary">Sign in</button>
      </form>



    </div>
  </body>
</html>

What this code does

  • formLogin(Customizer.withDefaults()) registers GET /login (a generated page) and POST /login (the check). logout(...) registers POST /logout. The users are the same in-memory BCrypt users as in the Basic lab.
  • A guest asking for /admin gets 302 to /login and a JSESSIONID cookie: the session was created to remember the page the guest wanted.
  • The login page already contains a hidden _csrf field; the CSRF lesson explains it. A browser posts it with the form automatically.

Example 2 · The whole login with curl and a cookie jar

Runs in: the session-lab practice project (Spring Boot 4.1)

Terminal
curl -i -c jar.txt http://localhost:8080/adminTOKEN=$(curl -s -b jar.txt -c jar.txt http://localhost:8080/login | sed -n 's/.*name="_csrf"[^>]*value="\([^"]*\)".*/\1/p')curl -i -b jar.txt -c jar.txt -d "username=asha.rao@example.com&password=wrong&_csrf=$TOKEN" http://localhost:8080/logincurl -i -b jar.txt -c jar.txt -d "username=asha.rao@example.com&password=Mango%232026&_csrf=$TOKEN" http://localhost:8080/logincurl -i -b jar.txt http://localhost:8080/admin
Sample output
$ curl -i -c jar.txt http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=5D88FDAD4452CCAC664B0A617E2203DE; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login
Content-Length: 0
Date: Fri, 16 Oct 2026 07:14:25 GMT

$ TOKEN=$(curl -s -b jar.txt -c jar.txt http://localhost:8080/login | sed -n 's/.*name="_csrf"[^>]*value="\([^"]*\)".*/\1/p')
$ echo $TOKEN
Ht-uqVNuBrBCdh3GD6wL_y40tbE37OX_BDppKdDonj5mq15ce7qfmDUMZIlvRX6jaoE_yhoBmIkBitzSZVteSrPf-lhQnjg9

$ curl -i -b jar.txt -c jar.txt -d "username=asha.rao@example.com&password=wrong&_csrf=$TOKEN" http://localhost:8080/login
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login?error
Content-Length: 0
Date: Fri, 16 Oct 2026 07:14:26 GMT

(fetch a fresh TOKEN from /login again, then sign in with the right password; %23 is # in a form body)

$ curl -i -b jar.txt -c jar.txt -d "username=asha.rao@example.com&password=Mango%232026&_csrf=$TOKEN" http://localhost:8080/login
HTTP/1.1 302
Set-Cookie: JSESSIONID=10F26E92CD35137B03CB894260F7BCE6; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/admin?continue
Content-Length: 0
Date: Fri, 16 Oct 2026 07:14:27 GMT

$ curl -i -b jar.txt http://localhost:8080/admin
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: text/plain;charset=UTF-8
Content-Length: 50
Date: Fri, 16 Oct 2026 07:14:27 GMT

Welcome to the admin console, asha.rao@example.com

What this code does

  • -c jar.txt saves cookies the server sets; -b jar.txt sends them back, as a browser does. -d posts form fields. The sed command copies the hidden _csrf value out of the login page.
  • A wrong password gives 302 to /login?error and keeps the same session. The right one gives 302 to the saved /admin?continue and a new JSESSIONID: session fixation protection at work.
  • The last call sends only the cookie, no password, and is let in.

The full trip, step by step:

  1. A guest asks for /admin. Spring saves that request in the session (the request cache) and answers 302 to /login.
  2. GET /login returns Spring's generated page: username and password fields plus a hidden _csrf field.
  3. The browser posts the three fields to /login. The UsernamePasswordAuthenticationFilter passes them to the AuthenticationManager, the same UserDetailsService and PasswordEncoder check as with Basic.
  4. Success: 302 to the saved page (/admin?continue), or to / if nothing was saved. Failure: 302 to /login?error.

Predict the output

Where does the redirect go?

Choose the Location header of the reply to POST /login.

Round 1 of 3

The password is wrong. What does Spring answer?

POST /login
username=asha.rao@example.com&password=wrong&_csrf=...
The ?continue part tells Spring to look for the saved request only on this one redirect, so other requests do not pay for that lookup.

The JSESSIONID cookie and the server-side HttpSession

An HttpSession is a small storage area that the server keeps in its memory for one browser. The JSESSIONID cookie carries the session's long random id, so the server can find that storage again on the next request.

The lab endpoint below prints the session behind the cookie, so you can see what the server keeps. The picture shows who holds what.

Form login with a session cookie. The browser posts the email and password to /login once. The server checks them, stores the signed-in user in a session in its own memory under a random id such as 5D88, and replies 302 with Set-Cookie: JSESSIONID=5D88.

Example 3 · src/main/java/com/shoplite/lab/admin/AdminController.java

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
package com.shoplite.lab.admin;
import java.util.Collections;import java.util.List;
import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContext;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpSession;
@RestControllerclass AdminController {
    record SessionView(String sessionId, int timeoutSeconds, List<String> attributes, String userInContext) {    }
    record ProductStatus(int id, boolean isActive, String changedBy) {    }
    @GetMapping("/admin")    String home(Authentication authentication) {        return "Welcome to the admin console, " + authentication.getName();    }
    /** What the server keeps for this browser: the HttpSession and the SecurityContext inside it. */    @GetMapping("/admin/session")    SessionView session(HttpSession session) {        SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");        return new SessionView(                session.getId(),                session.getMaxInactiveInterval(),                Collections.list(session.getAttributeNames()),                context.getAuthentication().getName());    }
    /** A state-changing action: it must never run because another website asked for it. */    @PostMapping("/admin/products/{id}/deactivate")    ProductStatus deactivate(@PathVariable int id, Authentication authentication) {        return new ProductStatus(id, false, authentication.getName());    }}
Sample output
$ curl -b jar.txt http://localhost:8080/admin/session
{"sessionId":"10F26E92CD35137B03CB894260F7BCE6","timeoutSeconds":900,"attributes":["SPRING_SECURITY_CONTEXT","SPRING_SECURITY_SAVED_REQUEST"],"userInContext":"asha.rao@example.com"}

$ cat jar.txt
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_localhost	FALSE	/	FALSE	0	JSESSIONID	10F26E92CD35137B03CB894260F7BCE6

What this code does

  • A controller can take the HttpSession as a parameter. The session holds SPRING_SECURITY_CONTEXT (the signed-in user) and SPRING_SECURITY_SAVED_REQUEST (the page asked for before login).
  • timeoutSeconds is 900: the 15 minutes from application.properties in Example 4. The cookie file holds just the id; everything else stays on the server.
  • The deactivate POST endpoint is used in the CSRF lesson.

After a successful login, Spring saves the SecurityContext (the signed-in user) in the session under the attribute name SPRING_SECURITY_CONTEXT. On every later request the SecurityContextHolderFilter reads the cookie, finds the session and puts that context back into the SecurityContextHolder. The password is checked once; after that the browser sends only the id.

A session id is as valuable as the password for as long as the session lives. Anyone who copies the cookie is signed in as that user, which is why the next three sections are about protecting it.

The lab endpoint in Example 3 prints the session id only so you can see it. A real app never returns or logs session ids.

Cookie flags: HttpOnly, Secure and SameSite

HttpOnly, Secure and SameSite are cookie flags: extra words in the Set-Cookie header that limit how the browser may use a cookie. HttpOnly hides it from JavaScript, Secure sends it only over HTTPS and SameSite stops most cross-site sending.

The session cookie is the key to the account, so its flags matter. Spring Boot sets them from the server.servlet.session.cookie.* properties.

Example 4 · src/main/resources/application.properties

Runs in: the session-lab practice project (Spring Boot 4.1)

Text
spring.application.name=session-lab# The session: how long an idle session lives, and the flags of its cookieserver.servlet.session.timeout=15mserver.servlet.session.cookie.http-only=trueserver.servlet.session.cookie.same-site=lax# true in production (HTTPS only); false here because localhost uses plain HTTPserver.servlet.session.cookie.secure=false
Sample output
With the settings above (secure=false on localhost); security headers left out:

$ curl -i http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=B23948098D6037BF84A97A86372E6DF4; Path=/; HttpOnly; SameSite=Lax
Location: http://localhost:8080/login

Started with --server.servlet.session.cookie.secure=true (the production setting):

$ curl -i http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=314A8DD3193C8B689087194C5439DFA1; Path=/; Secure; HttpOnly; SameSite=Lax
Location: http://localhost:8080/login

Started with --server.servlet.session.cookie.same-site=strict:

$ curl -i http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=B0D6E5BA4805D4ED5E56648134240AEC; Path=/; HttpOnly; SameSite=Strict
Location: http://localhost:8080/login

What this code does

  • Each property becomes one flag in Set-Cookie. HttpOnly and SameSite=Lax are on; Secure appears only when secure=true.
  • The --server.servlet.session.cookie.secure=true style of start-up argument overrides one property for one run, which is how the second and third replies were made.
  • In a real project, keep secure=true in the main file and switch it off only in a local development profile, never the other way round.

What each setting does:

  • HttpOnly: JavaScript on the page cannot read the cookie through document.cookie, so an XSS bug cannot copy the session id. Tomcat sets it by default; keep it.
  • Secure: the browser sends the cookie only over HTTPS, never over plain HTTP. Turn it on in production; browsers and curl treat http://localhost as secure, so it even works on your laptop.
  • SameSite=Lax: the cookie is not sent with requests that other sites start in the background or with forms they post, but it is still sent when the user clicks a link to your site. Strict never sends it on any request started from another site, and None always sends it and needs Secure.
  • No Expires or Max-Age: a session cookie, deleted when the browser is closed. The server-side timeout decides how long the login really lasts.

Logout, session fixation protection and session timeout

Session fixation is an attack where someone gets a session id first and tricks the victim's browser into using it, so the attacker shares the signed-in session. Spring prevents it by issuing a new session id at login.

Three settings decide how long a stolen or forgotten cookie stays useful: logout, a new session id at login, and an idle timeout. Example 5 changes the first two.

Example 5 · Logout, a new id and an idle timeout

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
// In SecurityConfig: replace the logout line with these settings.logout(logout -> logout.deleteCookies("JSESSIONID"))       // also remove the cookie.sessionManagement(session -> session    .sessionFixation(fixation -> fixation.changeSessionId()));  // the default, written out
Sample output
1) Logout with the default settings (jar.txt is signed in; old.txt is a copy of it)

$ TOKEN=$(curl -s -b jar.txt http://localhost:8080/logout | sed -n 's/.*name="_csrf"[^>]*value="\([^"]*\)".*/\1/p')
$ curl -i -b jar.txt -c jar.txt -d "_csrf=$TOKEN" http://localhost:8080/logout
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login?logout
Content-Length: 0
Date: Fri, 16 Oct 2026 07:14:29 GMT

$ curl -i -b old.txt http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=3E23EA9C2283C34A872010F4D44D4073; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login
Content-Length: 0
Date: Fri, 16 Oct 2026 07:14:29 GMT

2) With the logout and session lines above, started with --server.servlet.session.timeout=1m

$ curl -b jar.txt http://localhost:8080/admin/session
{"sessionId":"EF3DAE33826E806701214DA81360738A","timeoutSeconds":60,"attributes":["SPRING_SECURITY_CONTEXT"],"userInContext":"admin@shoplite.example"}

(no requests for 70 seconds)

$ curl -i -b jar.txt http://localhost:8080/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=130836F81FDD28037F2CB17F4616B635; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:50 GMT

(sign in again, then log out)

$ curl -i -b jar.txt -c jar.txt -d "_csrf=$TOKEN" http://localhost:8080/logout
HTTP/1.1 302
Set-Cookie: JSESSIONID=; Expires=Thu, 01 Jan 1970 00:00:10 GMT; Path=/; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login?logout
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:55 GMT

What this code does

  • Part 1 uses the default logout: the session is gone, so the copied cookie in old.txt only earns a redirect to /login. The token for the logout form came from Spring's GET /logout confirmation page.
  • Part 2: after 70 idle seconds the 1-minute session has expired and the same cookie is sent to /login again. With deleteCookies, logout also sends a Set-Cookie with an expiry date in 1970, which makes the browser delete it.

POST /logout (with the CSRF token, like any POST) invalidates the session, clears the context and redirects to /login?logout. The old cookie still sits in the browser but points to nothing, and logout.deleteCookies("JSESSIONID") also tells the browser to drop it. Logout is a POST so that another website cannot log you out with a hidden image link.

Spring's default, changeSessionId(), gives a new id at login; in Example 2 5D88... became 10F2..., so an id planted before login is worthless. The idle timeout, server.servlet.session.timeout=15m, restarts on every request, and Tomcat counts it in whole minutes.

Why sessions are harder to scale across several servers

Sticky sessions mean the load balancer always sends one browser to the same copy of the app, because that copy holds the browser's session in its memory.

ShopLite will run as several copies behind a load balancer. Example 6 starts two copies on one laptop and signs in on only one of them.

Example 6 · Two copies of the app do not share sessions

Runs in: the session-lab practice project (Spring Boot 4.1)

Terminal
java -jar target/session-lab-0.0.1-SNAPSHOT.jar --server.port=8081 &java -jar target/session-lab-0.0.1-SNAPSHOT.jar --server.port=8082 &# sign in on 8081 as in Example 2, saving the cookie in jar.txt, then:curl -b jar.txt http://localhost:8081/admincurl -i -b jar.txt http://localhost:8082/admin
Sample output
(two copies of session-lab: one on 8081, one on 8082; jar.txt signed in on 8081)

$ curl -b jar.txt http://localhost:8081/admin
Welcome to the admin console, admin@shoplite.example

$ curl -i -b jar.txt http://localhost:8082/admin
HTTP/1.1 302
Set-Cookie: JSESSIONID=E5F5833883D679F2509C76E9320D585D; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8082/login
Content-Length: 0
Date: Fri, 16 Oct 2026 07:29:03 GMT

What this code does

  • Cookies belong to the host name, not the port, so curl sends the same JSESSIONID to both copies, just as a load balancer would forward it.
  • Copy 8081 knows the id; copy 8082 has never seen it and treats the user as a guest. Behind a load balancer the user would be thrown out at random.

A session lives in the memory of one server. A load balancer is a server that spreads requests across the copies, so the next request can land on a copy that has never seen that session, and the user is sent back to the login page.

There are three common fixes, each with a cost. Sticky sessions: a restart or crash of the chosen copy still logs everyone on it out, and the load is uneven. A shared session store: Spring Session keeps sessions in Redis or a database table (spring-session-jdbc), so any copy can read them, but every request now needs that store. Or no session at all: a signed token that any copy can check, as the last lesson of this module explains.

Next step

Check your understanding

11 quick questions