Authentication: Sessions, Tokens, OAuth 2.0/OIDC, and Where Login State Should Live
System Design series · Part 8 Security (1 of 5)
- Authentication: Sessions, Tokens, OAuth 2.0/OIDC, and Where Login State Should Live
- Authorization Models and the OWASP API Top 10: What You Can Do After Logging In
- After BOLA Gets Past the BFF: How Microservices Pass Along Who Is Calling and for Whom
- Encryption in Transit and at Rest, and Secrets Management: What Encryption Protects Depends on Who Can Get the Key
- Abuse Prevention: Making Scalping, Credential Stuffing, and Fake Accounts Unprofitable for Adversaries Who Adapt
System Design series Part 8-1 | Previous: Batch and Stream Processing | Next: Authorization Models and the OWASP API Top 10 | Series map
Scenario and problem
The talk platform now has four kinds of login needs:
- Members: sign up, pay, and view their own tickets on the web (SPA) and in the mobile app
- Speakers: manage talks and view sign-up lists and revenue share in the back office
- Enterprise customers: want their employees to log in with company accounts (SSO); when someone leaves and the company disables the account, that person must no longer be able to log in
- Service to service: the sign-up service calls the payment service (Part 7), and the payment service needs to know “who is calling, and on whose behalf”; that waits until 8-3
In the STRIDE table in the series introduction, the first row is “spoofing”: signing up on someone else’s behalf with a stolen account. Authentication answers “who sent this request”, and it has to answer under these constraints:
- Every API request needs to know who it comes from, without checking the password every time
- When a user clicks log out, an admin disables an account, or an enterprise customer’s employee leaves, how fast does it take effect?
- The application runs on several machines (the stateless services post); where does login state live?
- If any piece of JavaScript on the page is injected, does the login state get stolen along with it?
- MembersMembers sign up, pay, and view their own tickets on the web (SPA) and in the mobile app.
- SpeakersSpeakers manage talks and view sign-up lists and revenue share in the back office.
- Enterprise SSOEnterprise customers want their employees to log in with company accounts. When someone leaves, the company disables the account, and that person can no longer log in.
- Every request must say whoEvery API request needs to know who it comes from, but it cannot check the password every time. The application runs on several machines, so where should login state live?
- How fast does it take effect?When a user logs out, an admin disables an account, or an employee leaves, how fast does it take effect? How much longer can login state that has already been issued keep working?
- Injected JavaScriptIf any piece of JavaScript on the page is injected, does the login state get stolen along with it?
Authentication answers only “who are you”; “what can you do” is authorization, the topic of the next post.
The simplest approach and its limits
Username and password login, with the session in the application’s memory
- Once you scale to two machines, a user logs in on machine A, the next request goes to machine B, and the user is logged out. Sticky sessions fix it for a while, but when you deploy or a machine crashes, every user on that machine is logged out (the Load Balancing post)
Sign your own JWTs, keep them in localStorage on the frontend, and send them in the Authorization header on every request
- The server keeps no state, so the scaling problem looks solved
- But a JWT stays valid until it expires. When a user logs out, changes a stolen password, or has the account disabled, tokens already issued still work
- Any injected JavaScript on the page can read
localStorageand send the token to the attacker’s server, and the attacker uses it on their own machine - Every application handles passwords and signs tokens on its own, and when an enterprise customer asks for SSO, you build it all over again
Core mechanism
Sessions vs tokens: where the state lives and how you revoke it
| Server-side session | Self-contained token (JWT) | |
|---|---|---|
| What the client gets | A random ID (usually in a cookie) | A signed set of claims: who, issued to whom, when it expires |
| How the server verifies it | Looks up the ID in the session store | Verifies the signature with a public key, no lookup needed |
| Revocation | Delete the session and the next request fails | Cannot be revoked before it expires, unless you also check a revocation list |
| Data updates | When permissions change, the data in the session can be updated with them | The claims in the token stay stale until it expires |
| Cost | One store lookup per request; if the store fails, nobody can authenticate | Every request carries a larger token; revocation is not immediate |
A rough estimate of both costs for the talk platform:
- Session store: 1 million active sessions. If a session holds only the user ID and permissions, that is about 1 KB each, 1 GB in total; if, like the BFF later in this post, the session holds the access token, refresh token, and ID token, it is about 3 to 4 KB each, 3 to 4 GB in total. At a peak of 20,000 requests per second, that is 20,000 Redis reads per second. One Redis instance can take it, but it becomes a component every request depends on (the Caching post covers Redis high availability)
- JWT: an RS256 token with a few claims is about 800 bytes to 1.5 KB. At 20,000 requests per second, the tokens alone add 20 to 30 MB/s of upstream traffic. The access token is valid for 10 minutes, which means that after you disable an account, it can keep calling the API for up to 10 more minutes in the worst case
So “session or JWT” is not a good question in itself. A better one is: which one for which hop. From the browser to the backend, use a session cookie; from the backend to APIs and between services, use short-lived tokens.
OAuth 2.0 and OpenID Connect
OAuth 2.0 solves delegated authorization: a user authorizes an application (the client) to access an API (the resource server) on their behalf, with limited permissions (scopes). The authorization server issues the client an access token, and the client calls the API with it.
OAuth by itself is not a login protocol: the access token is meant for the API, the client should not interpret it, and the client cannot reliably learn “who logged in” from it. OpenID Connect (OIDC) adds an ID token on top of OAuth 2.0: a JWT meant for the client that says who the user is (sub), who authenticated them (iss), which client it was issued to (aud), and when the authentication happened.
| Token | Meant for | Purpose | Common mistake |
|---|---|---|---|
| ID token | client | Confirms who logged in | Using the ID token to call an API |
| Access token | resource server (API) | Authorizes access to the API | The client reads the access token’s contents to identify the user |
| Refresh token | authorization server | Gets a new access token | Kept in the browser, not rotated |
The authorization code flow and PKCE
The only recommended flow for user login today is Authorization Code + PKCE:
sequenceDiagram
participant B as Browser
participant F as BFF (talk platform backend)
participant A as Authorization server (IdP)
participant R as Sign-up API
B->>F: Click log in
F->>F: Generate state and code_verifier, store them in the session
F-->>B: 302 redirect to the IdP, with code_challenge
B->>A: Log in (password, passkey, enterprise SSO)
A-->>B: 302 redirect back to the BFF, with code and state
B->>F: code and state
F->>F: Compare state
F->>A: code + code_verifier + client credentials
A-->>F: ID token, access token, refresh token
F-->>B: Set-Cookie (session ID only)
B->>F: Later requests carry the cookie
F->>R: Call the API with the access token
- PKCE (RFC 7636): the client first generates a random
code_verifierand puts only its hash (code_challenge) in the authorization request; when it exchanges the code for tokens, it sends the originalcode_verifier. Even if the authorization code is intercepted on the redirect back, whoever intercepted it cannot get tokens without thecode_verifier. RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025) requires PKCE for public clients, recommends it (RECOMMENDED) for confidential clients that have client credentials as well, and requires authorization servers to support PKCE state: binds the authorization response to the browser session that started the login, which stops an attacker from injecting their own authorization code into your login flow- Exact redirect URI matching: the authorization server accepts only a redirect URI that was registered in advance and matches exactly, with no wildcard or prefix matching; otherwise the authorization code can end up at the attacker’s URL
- Flows you should no longer use: the implicit grant (the token goes straight into the URL fragment) and resource owner password credentials (the client collects the user’s password directly) are both listed by RFC 9700 as not to be used
Browser apps: keep tokens out of the browser
RFC 10017 (OAuth 2.0 for Browser-Based Applications, published as a Best Current Practice in August 2026) lays out three architectures, from most to least secure:
| Architecture | Where the tokens are | When JavaScript is injected |
|---|---|---|
| Backend for Frontend (BFF) | Only on the backend; the browser has only an HttpOnly session cookie | The attacker can send requests from the victim’s browser, but cannot take the tokens away |
| Token-mediating backend | The backend obtains the tokens and hands them to the frontend | Tokens can be read and taken |
| Frontend as the OAuth client | The frontend | Tokens can be read and taken; the attacker can even run its own authorization flow in a hidden iframe and get brand-new tokens |
RFC 10017 points out that once an attacker can run JavaScript on the page, that code has the same privileges as the legitimate application code. Putting tokens in localStorage, sessionStorage, or memory does not stop it, because the attacker can simply get new tokens. The value of a BFF is that there are no tokens in the browser at all: the attacker is limited to “sending requests as the victim while the victim has the page open”, and cannot take credentials away to use long-term.
The BFF’s session cookie follows RFC 10017’s recommendations: Secure, HttpOnly, SameSite=Strict (often relaxed to Lax when external links need to land directly on logged-in pages), a name with the __Host- prefix, Path=/, and no Domain. The __Host- prefix makes the browser reject any cookie with that name that has a Domain attribute or is not Secure, so subdomains cannot overwrite it.
Using cookies means defending against CSRF: SameSite blocks most cross-site requests, and state-changing requests also get a CSRF token check.
Mobile apps have no BFF to hide tokens in. Per RFC 8252, the app runs the authorization code flow with PKCE through the system browser (not a WebView embedded in the app) and keeps tokens in the secure storage the operating system provides.
The token lifecycle
- Keep access tokens short: 5 to 15 minutes. That is the cap on the damage when one is stolen, and the cap on how long revocation takes
- Rotate refresh tokens: every time a refresh token is used, the authorization server issues a new one and invalidates the old one. If an invalidated refresh token is used again, two parties hold the same token (one of them is the attacker), and the authorization server should revoke the whole chain of refresh tokens and force a new login (RFC 9700)
- Bind tokens to their holder: an ordinary bearer token works for whoever has it. DPoP (RFC 9449) and mTLS binding (RFC 8705) bind the token to the client’s key, so a stolen token is useless without the matching private key (for DPoP in Spring Security, see DPoP in practice)
- Logout: the BFF deletes the session, calls the authorization server’s revocation endpoint (RFC 7009) to invalidate the refresh token, and ends the login at the IdP with OIDC RP-Initiated Logout. Access tokens already issued stay valid until they expire, which is why they must be short
Passwords, MFA, and passkeys
If you store passwords yourself, the rules in NIST SP 800-63B Rev. 4 (2025) go against many long-standing habits:
- With password-only login, the minimum is 15 characters; as part of multi-factor authentication, the minimum is 8 characters. Allow at least 64 characters
- Must not impose composition rules such as mixing upper and lower case, digits, and symbols
- Must not require periodic password changes; force a change only when there is evidence the password has been compromised
- When a password is set, check it against a blocklist (breached passwords, dictionary words, the service’s name), and explain why when you reject one
- Do not offer password hints that can be seen without logging in, and do not use security questions
- Cap consecutive failed attempts on one account at no more than 100
Store passwords salted, with a hash function that has a cost parameter. OWASP recommends Argon2id (for example 19 MiB of memory, 2 iterations, parallelism 1), followed by scrypt and bcrypt. bcrypt uses only the first 72 bytes, and long Unicode passwords can exceed that.
Passkeys (WebAuthn) sign the server’s challenge with a private key on the device, and the signature is bound to the site’s domain: if a user “logs in” on a phishing site, the signature it produces is invalid on the real site. This is currently the most practical phishing-resistant way to authenticate. SMS and ordinary one-time passwords stop password reuse, but they cannot stop a phishing site that relays them in real time.
Enterprise SSO: identify people by iss plus sub, not by email
Employees of enterprise customers log in through their own company’s IdP (OIDC or SAML), and the talk platform becomes a client of that IdP. When an employee leaves, the company disables the IdP account and the next login fails; but sessions the talk platform has already issued do not end on their own, so sessions for enterprise accounts should be shorter than for regular members, or the platform should support the IdP’s logout notifications.
The most common mistake is matching accounts by email: “This IdP says the user is alice@example.com, and the database happens to have that email, so log them into that account.” Any IdP that lets users set their own email, or does not verify email, can then be used to take over someone else’s account. The unique identifier of an external identity is iss plus sub; linking an external identity to an existing account must be an explicit action taken while the user is already logged in.
Comparing options
| Option | Fits | Revocation | Cost |
|---|---|---|---|
| Session cookie (monolith) | Server-rendered or same-domain monoliths | Immediate | Needs a shared session store |
| BFF + session cookie | SPAs that handle personal data or payments | Session immediate; access token by its lifetime | One more backend component; larger sessions |
| JWT access token | APIs, resource servers | By its lifetime, or add a revocation list | Larger tokens; permission changes are not immediate |
| Opaque token + introspection (RFC 7662) | APIs that need immediate revocation | Immediate | Every request asks the authorization server; you usually add a cache, which brings delayed revocation back |
The talk platform’s choices:
- Identity provider: use a managed IdP or self-host a mature implementation (Keycloak, Spring Authorization Server), instead of handling passwords and issuing tokens in every application. Enterprise customers federate with this IdP through OIDC or SAML
- Web: a Spring Boot BFF with
oauth2Loginplus Spring Session (Redis); the browser has only a session cookie whose name starts with__Host- - Mobile app: system browser plus PKCE; 10-minute access tokens, rotating refresh tokens
- Each API: a resource server that verifies the JWT’s signature,
iss,aud, andexp - Members: offer passkeys; require multi-factor authentication for speakers and admins
In Java
1. BFF: login, sessions, and forwarding tokens
spring:
security:
oauth2:
client:
registration:
lectures:
client-id: lectures-web
client-secret: ${idp.lectures-web.client-secret} # read by configtree from a mounted secrets file, not written in the config file (8-4)
authorization-grant-type: authorization_code
scope: openid, profile, lectures.read, lectures.register
provider:
lectures:
issuer-uri: https://id.lectures.example.com/realms/lectures
session:
timeout: 8h
server:
servlet:
session:
cookie:
name: __Host-SESSION
secure: true
http-only: true
same-site: lax@Configuration
@EnableWebSecurity
public class BffSecurityConfig {
@Bean
SecurityFilterChain bffFilterChain(HttpSecurity http, ClientRegistrationRepository registrations) throws Exception {
OidcClientInitiatedLogoutSuccessHandler logoutSuccess =
new OidcClientInitiatedLogoutSuccessHandler(registrations);
logoutSuccess.setPostLogoutRedirectUri("{baseUrl}/");
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/assets/**").permitAll()
.anyRequest().authenticated())
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout.logoutSuccessHandler(logoutSuccess))
.csrf(csrf -> csrf.spa()); // the SPA reads the CSRF token from a cookie and puts it in a request header
return http.build();
}
/** Adds the current user's access token when calling downstream APIs; gets a new one with the refresh token when it expires. */
@Bean
RestClient lecturesApiClient(OAuth2AuthorizedClientManager authorizedClientManager) {
OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
interceptor.setClientRegistrationIdResolver(request ->
SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2AuthenticationToken token
? token.getAuthorizedClientRegistrationId()
: null);
return RestClient.builder()
.baseUrl("http://registration.lectures.svc.cluster.local")
.requestInterceptor(interceptor)
.build();
}
}- Add
spring-boot-starter-session-data-redisand sessions are stored in Redis, so the BFF can scale horizontally - On a successful login, Spring Security changes the session ID by default (
changeSessionId), which prevents session fixation OAuth2AuthorizedClient(which holds the access token and refresh token) is stored in the session by default, which is exactly why the BFF’s sessions are larger- The BFF is a confidential client, and you still need to make sure its authorization requests carry PKCE. Spring Security controls this with the
requireProofKeysetting on the client registration; also confirm that the IdP supports it
2. API: verifying JWT access tokens
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://id.lectures.example.com/realms/lectures
audiences: registration-api@Configuration
@EnableWebSecurity
public class ResourceServerConfig {
@Bean
SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.POST, "/v1/registrations").hasAuthority("SCOPE_lectures.register")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}issuer-urilets Spring Security find the JWKS location in the IdP’s discovery document and verifyiss;audiencesverifies thataudincludes this API. Without theaudcheck, tokens issued for other services can also be used to call this API- The signing algorithm and the public keys both come from the configured IdP; a key location named in the token header is not used
- The API does not use sessions, so it needs no CSRF protection: it accepts only tokens in the
Authorizationheader, which browsers do not attach automatically
3. Passwords and passkeys when you run your own IdP
@Bean
PasswordEncoder passwordEncoder() {
String defaultId = "argon2";
Map<String, PasswordEncoder> encoders = Map.of(
defaultId, Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(),
"bcrypt", new BCryptPasswordEncoder());
// New passwords use Argon2id; old {bcrypt} hashes still verify, and with UserDetailsPasswordService they can be upgraded on a successful login
return new DelegatingPasswordEncoder(defaultId, encoders);
}
@Bean
SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
http
.formLogin(Customizer.withDefaults())
.webAuthn(webAuthn -> webAuthn
.rpId("lectures.example.com")
.allowedOrigins("https://lectures.example.com"));
return http.build();
}Argon2PasswordEncoderneeds the Bouncy Castle library- Spring Security 7 supports multi-factor authentication (
@EnableMultiFactorAuthentication,FactorGrantedAuthority), so you can require both factors, a password and a passkey, for the speaker back office
The configuration and code above follow the official Spring Boot 4.1 and Spring Security 7.1 documentation and have not been compiled or run. For the details of issuing your own JWTs, see Issuing your own JWTs with Spring Security; the frontend example in that post keeps the token in
localStorage, and under this post’s threat model, web apps that handle personal data or payments should use a BFF instead.
Pitfalls and gotchas
- Treating an ID token as an access token: the API receives an ID token and lets it through because the signature is valid and it has not expired, but its
audis the client, not this API - Too many permissions in the JWT: permission changes take effect only when the token expires; when the token gets too large, it exceeds the proxy’s header size limit and the request is rejected outright
- JWKS caching: after the IdP rotates its keys, the API is still using the old public key. When it meets an unknown
kid, it has to fetch the JWKS again (Spring Security’s decoder handles this), but you also need to limit how often it refetches - Clock skew: when servers are a few seconds apart, a freshly issued token is judged “not yet valid”. Allow a small skew when validating (60 seconds by default in Spring Security)
- The session store is a single point of failure: when Redis stops, no user can authenticate. Keep the session store separate from other caches, and design it for high availability
- Concurrent token refresh: several tabs or concurrent requests exchange the same refresh token at the same time; with rotation and reuse detection enabled, the second request is treated as an attack and the user is logged out. The BFF must make sure only one refresh per session is in flight
- Logout only deletes the browser’s cookie: the server-side session and the refresh token are both still valid
- Disabled enterprise accounts can still log in: the talk platform’s session outlives the account at the IdP
Attack scenarios
| Attack | How it happens | Defense |
|---|---|---|
| Credential stuffing | Mass login attempts with usernames and passwords leaked from other sites. The attacker tries each account only once or twice, so a per-account failure limit does not stop it | Check passwords against breach lists when they are set; rate limit by IP, device, and overall failure rate (the Rate Limiting post, 8-5); MFA and passkeys |
| Phishing | A fake login page relays the username, password, and one-time password in real time | A passkey’s signature is bound to the domain and is invalid on the fake site |
| Token theft via XSS | An injected script reads the token and takes it away | BFF, so there are no tokens in the browser; CSP reduces the chance of XSS |
| CSRF | Another site makes the logged-in browser send a state-changing request | SameSite cookies plus CSRF tokens |
| Session fixation | The attacker first gets the victim to use a known session ID, then waits for them to log in | Change the session ID at login |
| JWT algorithm attacks | Change the header to alg: none, or switch RS256 to HS256 and use the public key as the HMAC secret; or point jku or kid at a key the attacker controls |
Pin the allowed algorithms, and get public keys only from the configured IdP (RFC 8725; for the verification steps see the JOSE post) |
| Token reused at another service | A token that a low-privilege service received is forwarded by that service (or by whoever compromised it) to a high-privilege API | Every API checks aud; when identity has to be passed downstream, use token exchange (8-3) |
| Authorization code interception or injection | A malicious app registers the same redirect scheme, or the attacker slips their own authorization code into the victim’s flow | PKCE, state, exact redirect URI matching |
| Account takeover via email | Register the victim’s email at an IdP that does not verify email, then log in with SSO | Identify external identities by iss plus sub; linking accounts must be an explicit action while logged in |
| Stolen refresh token | A long-lived refresh token leaks from a device or from logs | Rotation and reuse detection; DPoP or mTLS binding |
| Account enumeration | “Account does not exist” and “wrong password” differ in message or response time | Login, sign-up, and forgot-password all return the same message, with similar processing time |
| Tokens in logs | The Authorization header, cookies, and URLs that carry tokens get logged |
Mask these fields in logs (the Observability post); never put tokens in URLs |
When to use it, and when not to
- Use session cookies: from the browser to your own backend. Use them directly in a monolith; in an SPA, use them through a BFF
- Use OAuth 2.0/OIDC: when several applications or APIs share one login, you need enterprise SSO, or third parties need to access an API on a user’s behalf
- Use short-lived JWT access tokens: between APIs and services, when you need to verify without a database lookup and can accept a revocation delay of a few minutes
- Don’t build it yourself: implementing your own OAuth authorization server, designing your own token format, inventing your own password hashing. Use a mature IdP and libraries, and spend the time on getting the configuration right
- When to re-evaluate: when a requirement for “immediate revocation” appears (for example financial transactions, or emergency handling of a hijacked account) and the delay of short-lived tokens is unacceptable, switch to opaque tokens plus introspection, or re-authenticate before sensitive operations
References
- RFC 6749, “The OAuth 2.0 Authorization Framework”
- RFC 7636, “Proof Key for Code Exchange by OAuth Public Clients”
- RFC 9700, “Best Current Practice for OAuth 2.0 Security”, January 2025
- RFC 10017, “OAuth 2.0 for Browser-Based Applications”, August 2026: https://www.rfc-editor.org/rfc/rfc10017
- RFC 8252, “OAuth 2.0 for Native Apps”
- RFC 8725, “JSON Web Token Best Current Practices”
- RFC 9449, “OAuth 2.0 Demonstrating Proof of Possession (DPoP)”; RFC 8705, “OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens”
- RFC 7009, “OAuth 2.0 Token Revocation”; RFC 7662, “OAuth 2.0 Token Introspection”
- OpenID Connect Core 1.0 and OpenID Connect RP-Initiated Logout 1.0: https://openid.net/developers/specs/
- NIST SP 800-63B Rev. 4, “Digital Identity Guidelines: Authentication and Authenticator Management”: https://pages.nist.gov/800-63-4/sp800-63b/authenticators
- OWASP Cheat Sheet Series — Password Storage, Session Management, Authentication: https://cheatsheetseries.owasp.org/
- Spring Security Reference — OAuth 2.0 Login, Resource Server JWT, Passkeys, Multi-Factor Authentication, CSRF: https://docs.spring.io/spring-security/reference/
- Further interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments