Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Security › Authentication

Sessions and JWT

Where is the login state stored?

Why it exists — An HTTP request knows nothing about the earlier requests, so if you do not want to send the password again with every request, you need a mark that says "this user has already logged in". A session solves this: the server stores the login record and finds it by the session ID. A JWT lets the server only verify a token that it signed, so even with many servers, it can identify the user without a shared store for login records.

Where it's used today — A web service where the server builds the pages commonly uses sessions, and when there are several servers, the sessions are kept in a shared store such as Redis. For mobile apps and for APIs where several services must verify the same login, JWT is commonly used. A token that has already been issued is hard to invalidate before it expires, so the access token is kept short and a new one is issued with a refresh token. On a Spring server, tokens are issued with JwtEncoder (NimbusJwtEncoder), which Spring Security provides, and the OAuth 2.0 resource server setup (oauth2ResourceServer) checks the signature and the expiration time on every request with JwtDecoder (NimbusJwtDecoder).

A logged-in user sends requests at 10-minute intervals, and a load balancer hands the requests to the servers in turn. See what happens when you add servers or force a logout, first when the server remembers the login state (a session) and then when the client carries it (a JWT).

Checked against real execution · The 72 combinations were run with nginx 1.27.5 (round robin), one to three Spring Boot 4.1.1 servers, and Redis 8.10.2, and the server that received each request, the response code, and the store accesses were checked. The session side ran the code on the screen with Spring Session 4.1.1, and the JWT side really ran NimbusJwtEncoder and NimbusJwtDecoder of Spring Security 7.1.1. The runs did not wait for the time to pass, and the clock on the JWT side was moved forward 10 minutes at a time

Concepts in this lab

Cookie
A small piece of data that a server sends in a response. The browser stores it and automatically sends it back with every request to the same site. HTTP does not remember state between requests, so this data is used to keep information that must carry over, such as a login state. Because it is stored in the user's browser, you must use it on the assumption that the user can read or change its contents.
Session
A way to store a user's state on the server side and give the client only an identifier (the session ID) that points to that stored state, delivered in a cookie. The actual information is on the server, so the client cannot change its contents (having the session ID stolen is a different problem). When there are several servers, a common setup keeps this state in a shared store such as Redis so that any server that receives a request can find the same state.
JSON Web Token (JWT)
A token that carries content such as user information (claims) and has a signature attached. It has three parts: a header, a payload, and a signature. The server verifies the signature to confirm that the token was not forged, and it does not need to look up a separate store. The payload is encoded, not encrypted, so anyone can read its contents. Do not put sensitive information in it.
JwtEncoder and NimbusJwtEncoder
Why it exists — If you build a token yourself, you have to get every step right by hand: write the header and the claims as JSON, convert them to base64url, sign them with a suitable algorithm, and join the parts. Spring added an interface on the issuing side to pair with JwtDecoder on the verifying side, so that once you decide the claims, the same library also does the signing.
Where it's used today — It is used on a server whose login API issues access tokens itself. If you register a JwtDecoder built with the same key as a bean and turn on http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())), the tokens it issued are verified on later requests. In a setup where an authorization server such as Google or Keycloak issues the tokens, the service server uses only JwtDecoder, without JwtEncoder.
JwtEncoder is an interface that Spring Security (spring-security-oauth2-jose) provides, and with one method, Jwt encode(JwtEncoderParameters parameters), it builds a token and signs it. What you pass in are the claims written with JwtClaimsSet.builder() (sub, iat, exp, and so on) and a header that fixes the signature algorithm, such as JwsHeader.with(MacAlgorithm.HS256). getTokenValue() of the returned Jwt is the token text to send down to the user. On failure it throws JwtEncodingException. NimbusJwtEncoder is the standard implementation that does this work with the Nimbus JOSE+JWT library. For a symmetric key (HS256) you build it with NimbusJwtEncoder.withSecretKey(key).build(), and for an RSA or EC key pair with withKeyPair(publicKey, privateKey) (both since Spring Security 7.0).
JwtDecoder and NimbusJwtDecoder
Why it exists — Verifying a JWT requires getting everything right: decoding base64url, fixing the algorithm, calculating the signature and comparing in constant time, key length, and the expiration time and clock skew. If you write it yourself, missing just one place lets a forged token pass. Spring leaves this work to a well-tested library and provides an interface that returns only the result, as a Jwt object and fixed exceptions.
Where it's used today — In Spring Boot, if you register a JwtDecoder as a bean and turn on http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())), BearerTokenAuthenticationFilter calls decode on every request and answers with 401 if it fails. To check iss or aud too, you pass a validator made with something like JwtValidators.createDefaultWithIssuer to setJwtValidator.
JwtDecoder is an interface that Spring Security (spring-security-oauth2-jose) provides, and with one method, Jwt decode(String token), it verifies the text of a token and turns it into a Jwt object. If verification fails, it throws an exception of the JwtException family. If the format, the algorithm, or the signature is wrong, it throws BadJwtException, and if the signature is correct but a validation rule such as the expiration time fails, it throws JwtValidationException, which inherits from BadJwtException. NimbusJwtDecoder is the default implementation that does this work with the Nimbus JOSE+JWT library. You build one for a symmetric key (HS256) with NimbusJwtDecoder.withSecretKey(key).build(), for a public key with withPublicKey(key), and for the key-list address of an authorization server with withJwkSetUri(uri). The default validator (JwtValidators.createDefault()) checks the typ header and the expiration and start times, and it allows a 60 second margin on the expiration time.
Access token and refresh token
Why it exists — When one token keeps a login going, a long lifetime means a stolen token stays usable for a long time, and a short lifetime means the user must log in again often. If you split it into an access token and a refresh token, the token that travels with every API request has a short life, and the login continues through the refresh token.
Where it's used today — It is commonly used in mobile apps and SPAs that keep a login with a JWT. The refresh token is often kept in an HttpOnly cookie or in the app's secure storage, and the server also records it and revokes it when the user logs out.
An access token is the token that a client presents when it calls an API. Its lifetime is kept short to reduce the damage if it is stolen. A refresh token is the token used to get a new access token when the access token expires. It has a long lifetime and is stored more securely. The server can revoke a refresh token to stop new access tokens from being issued.
HTTP as a stateless protocol
Why it exists — If the server had to remember the earlier conversation for each request, the resources needed to keep that memory would grow with the number of users, and a conversation could not continue once a connection was cut. HTTP is defined so that a request can be handled by looking at that request alone, so the server does not have to remember anything between requests.
Where it's used today — Receiving web pages and images, a mobile app calling a server API, and a server calling another service's API are all done over HTTP. For features like chat, in which the server also has to send data first at any time, WebSocket is used together with it.
HTTP is a communication protocol in which a client sends a request and a server responds. Stateless means that the server does not remember the content of earlier requests, so each request must carry all the information needed to process it. Because the server keeps no state, any server can take a request, which makes it easy to add servers. Information that must carry over, such as a login state, is kept with cookies, sessions, or tokens.

Try these

Running with the default settings

  1. 0 min: The user logged in on Server 1. Server 1 creates a session in its own memory and sends the session ID down in a cookie. Only Server 1 remembers this user.
  2. 10 min: The request went to Server 2. It sent the session ID in the cookie, but this server has no such session in its memory, so it treats the user as not logged in.
  3. 20 min: The request went to Server 1. This server has session abc123 in its memory, so it treats the user as logged in.
  4. 30 min: The request went to Server 2. It sent the session ID in the cookie, but this server has no such session in its memory, so it treats the user as not logged in.
  5. 40 min: The request went to Server 1. This server has session abc123 in its memory, so it treats the user as logged in.
  6. 50 min: The request went to Server 2. It sent the session ID in the cookie, but this server has no such session in its memory, so it treats the user as not logged in.

Result of this run

Code

// Only the needed parts are kept (login and later requests are handled in different methods)

// On successful login
HttpSession session = request.getSession();
session.setAttribute("memberId", member.getId());
// Response header: Set-Cookie: JSESSIONID=abc123; HttpOnly

// On every later request: find the session by the session ID in the cookie
HttpSession session = request.getSession(false);
if (session == null) {
    throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);   // an exception provided by Spring -> 401 response
}

Assumptions of this model

It assumes that the load balancer sends requests to the servers in turn (the login goes to Server 1, the next request to Server 2, and so on). The request for a new token and the request that is sent again are also requests, so each of them moves the turn forward by one. All 72 combinations were run with real software, and it was confirmed that the server that received each request, the response code, and whether the shared store was reached match the screen. The load balancer is an upstream of nginx 1.27.5 (round robin, the default method), the servers are one to three Spring Boot 4.1.1 servers, and the shared store is Redis 8.10.2. The session code was run exactly as on the screen, and the Redis session setup adds the modules that spring-boot-starter-session-data-redis brings in (Spring Session 4.1.1 and others). It was also confirmed by running that the session stays in server memory when only spring-session-data-redis is added without the session module of Spring Boot, and that a request with the session cookie ends with 500 when Redis is stopped. For the JWT code, NimbusJwtEncoder (issuing) and NimbusJwtDecoder (verifying, nimbus-jose-jwt 10.9.1) of Spring Security 7.1.1 were really run, and the token of each request was verified by BearerTokenAuthenticationFilter on a server with oauth2ResourceServer turned on. An expired token got a 401 with the reason "Jwt expired at …". The runs did not really wait 50 minutes. On the session side the requests were sent one after another in order, and the session timeout was set to 60 minutes and assumed not to be reached within these 50 minutes (the default of Spring Boot is 30 minutes). On the JWT side the issuing code and the JwtTimestampValidator of the decoder were given the same clock, and that clock was moved forward 10 minutes at a time. The decoder allows 60 seconds of clock skew on the expiration time by default, but every request in this lab is at least 5 minutes away from the expiration time, so the results do not change. "Shared store accesses" in the result table is the number of requests and operations that reached the store. Each of them sends several Redis commands, and in the test run Spring Session sent 5 or 6 commands (HGETALL, EXISTS, HMSET, PEXPIREAT) for one request from a logged-in user. Issuing and storing the refresh token (in Redis, expiring after 14 days), issuing a new token, and the forced logout by the administrator were run with code written as an example. Keeping the refresh token in a server store and checking it there is a widely used setup, but no standard requires it. The session ID abc123 and the refresh token r-001 are short values written for explanation, and the real values are long random strings.

Next lab: Cookies

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these