The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·50

Spring Security and Modern Identity

Authentication and authorisation from first principles, then Spring Security's architecture: the SecurityFilterChain, authentication managers and providers, password storage, roles versus authorities, method security, sessions, CSRF and CORS. Then modern identity: OAuth 2.0 flows, OpenID Connect, JWTs and their pitfalls, resource servers, authorisation-server concepts, PKCE, the BFF pattern, and service-to-service authentication (client credentials, mTLS, workload identity). Compared with ASP.NET Core, Go and Rust middleware, FastAPI, NestJS/Passport and Phoenix.

31 topics · ~28 min read · 30-question quiz
Updated Suggest a correction

Start here: who are you, and what may you do?

Two questions

Every protected request answers two questions, in order:

  1. Authentication: who is calling? Prove an identity with something the caller knows (a password), has (a phone, a passkey, a private key) or a token issued after one of those.
  2. Authorisation: is this caller allowed to do this? Check roles, permissions or ownership ("can Asha see order 101? only if it's hers").

The HTTP status codes follow the same split: 401 Unauthorized means "I don't know who you are" (really unauthenticated; it comes with a WWW-Authenticate header saying how to authenticate), and 403 Forbidden means "I know who you are, and you may not do this". Getting them the right way round matters to clients: a 401 tells them to sign in again, a 403 tells them not to bother.

A complete flow, by hand

Java
// passwords: stored only as salted, slow hashes
static String hash(String password, byte[] salt) {
    var f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    byte[] h = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 600_000, 256)).getEncoded();
    return base64(salt) + ":" + base64(h);
}
// login: verify the password, then issue a signed token valid for 15 minutes
@PostMapping("/login") … if (u == null || !matches(l.password(), u.passwordHash())) → 401 … else return issue(u);
// a filter on every request: verify the token's signature and expiry, remember who the caller is
if (auth.startsWith("Bearer ")) { var claims = verify(auth.substring(7)); req.setAttribute("user", claims.get("sub")); … }
// endpoints decide what each caller may do
@GetMapping("/menu")          → public
@GetMapping("/me")            → any signed-in user, else 401
@GetMapping("/kitchen/queue") → role STAFF, else 403
Text
$ curl localhost:8099/menu                                          ["Masala dosa","Filter coffee"]                 [HTTP 200]
$ curl localhost:8099/me                                            {"title":"Unauthorized"}                         [HTTP 401]
$ curl -X POST localhost:8099/login -d '{"username":"asha","password":"guess"}'
                                                                    {"title":"Unauthorized","detail":"bad credentials"}  [HTTP 401]
$ curl -X POST localhost:8099/login -d '{"username":"asha","password":"correct horse battery"}'
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwicm9…","token_type":"Bearer","expires_in":"900"}
   token payload, base64-decoded: {"sub":"asha","roles":"CUSTOMER","exp":1793285963}

$ curl localhost:8099/me -H "Authorization: Bearer $ASHA"            {"user":"asha","roles":["CUSTOMER"]}             [HTTP 200]
$ curl localhost:8099/kitchen/queue -H "Authorization: Bearer $ASHA" {"title":"Forbidden","detail":"requires role STAFF"}  [HTTP 403]
$ curl localhost:8099/kitchen/queue -H "Authorization: Bearer $RAVI" ["order 101: 2 × Masala dosa"]                 [HTTP 200]
$ curl … -H "Authorization: Bearer $FORGED"     (payload edited to say STAFF)
                                                                    {"title":"Unauthorized","detail":"bad signature"} [HTTP 401]

Four ideas carry the whole chapter:

  • Passwords are never stored, only slow, salted hashes. Verifying took about 150 ms on purpose (600,000 PBKDF2 iterations), so an attacker who steals the table can try only a handful of guesses per second per core instead of millions (lab experiment 1). Compare hashes in constant time (MessageDigest.isEqual).
  • A token is a signed claim, here a JWT (JSON Web Token): base64 header, payload and an HMAC signature. Anyone can read the payload (it isn't encrypted), but changing it breaks the signature, as the forged token showed. Tokens expire (15 minutes here), so a stolen one is useful only briefly.
  • Authentication happens once, in a filter, before any controller runs; controllers just ask "who is this?" and "what may they do?".
  • Deny by default: every endpoint should require authentication unless it's deliberately public.

The same thing with Spring Security

Spring Security replaces each hand-written piece with tested components, wired as a chain of filters:

Java
@Bean SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(a -> a
            .requestMatchers("/menu").permitAll()
            .requestMatchers("/kitchen/**").hasRole("STAFF")
            .anyRequest().authenticated())                          // deny by default
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))   // verify Bearer JWTs (signature, expiry, issuer)
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .build();
}
@Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }   // bcrypt by default

In a real system, the service usually doesn't issue tokens or store passwords at all: users sign in at an identity provider (Keycloak, Okta, Auth0, Microsoft Entra ID, Google) using OAuth 2.0 and OpenID Connect, and the service only verifies the tokens it receives, as a resource server. The full-depth sections explain those protocols, sessions versus tokens, and browser protections (CSRF and CORS), which the lab demonstrates in a real browser.

How deep to go in security and identity

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain authentication vs authorisation, 401 vs 403, password hashing and tokens
L2 Configure Spring Security filter chains, password encoders, method security and a JWT resource server
L3 Explain sessions vs tokens, OAuth 2.0 flows with PKCE, OpenID Connect, JWT validation, CSRF, CORS and the BFF pattern
L4 Diagnose broken access control, token validation gaps, CSRF and CORS misconfigurations
L5 Design identity and access for a product (IdP choice, scopes, roles, service-to-service auth)
L6 Set organisation-wide identity standards, reviews and incident response for auth failures

Foundations

Authentication versus authorisation

  • Authentication (authN): who are you? Verifying an identity through a password, a passkey, an OTP, a certificate, or a token from an identity provider.
  • Authorisation (authZ): what may you do? Deciding whether an authenticated principal can perform an action on a resource.

They fail differently: 401 Unauthorized means "not authenticated" (the name is a historical accident), and 403 Forbidden means "authenticated, not allowed" (chapter 45). Keep the concepts separate in code. Authentication produces a principal (identity plus attributes or claims). Authorisation is a policy decision over (principal, action, resource, context).

Authorisation models:

Model Decision based on Example
RBAC (role-based) The roles a user has ADMIN can delete orders
Permission / authority-based Fine-grained permissions (often grouped into roles) orders:delete
ABAC (attribute-based) Attributes of user, resource and environment "Managers can approve expenses < €5,000 in their own department during business hours"
ReBAC (relationship-based, Google Zanzibar style) Relationships in a graph "Can view doc if viewer of the doc's folder, or member of a group that is" (OpenFGA, SpiceDB, Permify)
Ownership checks Resource ownership Users can read only their own orders. Forgetting this is the #1 API vulnerability: BOLA/IDOR, OWASP API Top 10 #1

Part X covers security broadly, including threat modelling and OWASP. This chapter focuses on how backend frameworks implement identity.

Spring Security's architecture

The SecurityFilterChain

Spring Security plugs into the servlet filter chain (chapter 48) as a single filter (DelegatingFilterProxy → FilterChainProxy), which delegates to one or more SecurityFilterChains. Each chain matches some requests and contains an ordered list of security filters:

DelegatingFilterProxy FilterChainProxy chain 1: /api/** (JWT) chain 2: /** (session) filters of the matched chain, in order: SecurityContextHolderFilter CorsFilter CsrfFilter LogoutFilter authentication (bearer / form / OAuth2) AnonymousAuthenticationFilter ExceptionTranslationFilter AuthorizationFilter → DispatcherServlet auth filters put an Authentication in the SecurityContext AuthorizationFilter decides; failures are translated: not authenticated → 401 · access denied → 403
Spring Security's filter architecture. The FilterChainProxy picks the first SecurityFilterChain whose matcher fits the request and runs its filters in order.

Modern configuration is component-based: declare SecurityFilterChain beans with the lambda DSL. The old WebSecurityConfigurerAdapter was removed in Spring Security 6, and the and()-chaining style was removed in 7:

Java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity                                         // @PreAuthorize etc.
class SecurityConfig {

    @Bean
    @Order(1)
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/catalog/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.POST, "/api/orders").hasAuthority("SCOPE_orders:write")
                .anyRequest().authenticated())                     // deny by default for everything else
            .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()))   // stateless bearer-token auth
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable())                          // OK ONLY because no cookies authenticate /api/**
            .cors(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/assets/**", "/login").permitAll()
                .anyRequest().authenticated())
            .oauth2Login(Customizer.withDefaults())                // OIDC login for the browser app (BFF, below)
            .logout(l -> l.logoutSuccessUrl("/"));                 // CSRF protection stays ON (cookies!)
        return http.build();
    }
}

Rules are evaluated in order, and the first match wins, so put specific rules before general ones and end with anyRequest().authenticated() or denyAll(). An allow-by-default configuration is how internal endpoints end up public.

Authentication internals

  • Authentication: the principal, credentials, authorities (GrantedAuthority), and whether it's authenticated.
  • SecurityContextHolder: holds the current SecurityContext (and thus the Authentication). It's ThreadLocal-based by default, so it doesn't propagate to new threads automatically. Use DelegatingSecurityContextExecutor, context propagation for reactive code, or structured concurrency with scoped values.
  • AuthenticationManager (usually ProviderManager) delegates to AuthenticationProviders: DaoAuthenticationProvider (username + password via a UserDetailsService + PasswordEncoder), JwtAuthenticationProvider, OAuth2 login providers, LDAP, and others.
  • Entry points (AuthenticationEntryPoint) start authentication when an unauthenticated user hits a protected resource: redirect to login, or return 401 with WWW-Authenticate: Bearer.
Java
// Accessing the current user in a controller
@GetMapping("/me")
UserDto me(@AuthenticationPrincipal Jwt jwt) { return new UserDto(jwt.getSubject(), jwt.getClaimAsString("email")); }
// or: SecurityContextHolder.getContext().getAuthentication()

Passwords

If you store passwords (preferably you don't: delegate to an identity provider), store them as slow, salted, adaptive hashes, never encrypted and never as plain fast hashes:

  • Fast hashes (SHA-256, MD5) are wrong: GPUs compute billions per second, so leaked databases get cracked.
  • Password hashing functions are deliberately expensive and salted (a random per-password salt defeats precomputed rainbow tables): Argon2id (the winner of the Password Hashing Competition, memory-hard; OWASP's first choice), scrypt (memory-hard), bcrypt (widely deployed; it uses only the first 72 bytes of input), and PBKDF2 (FIPS-approved; needs very high iteration counts).
  • Tune the cost so hashing takes roughly 100 ms or more on your servers, and raise it over time.
Java
@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();   // default bcrypt; stores "{bcrypt}$2a$10$…"
}
// The {id} prefix lets you UPGRADE algorithms: verify old hashes and re-encode on login (upgradeEncoding()).
// Argon2: new Argon2PasswordEncoder(16, 32, 1, 1 << 16, 3) (needs Bouncy Castle)

Other languages: Go golang.org/x/crypto/argon2 or bcrypt, Rust argon2 (RustCrypto) or password-hash, .NET PasswordHasher<T> (PBKDF2) or the Konscious Argon2 library, Python argon2-cffi/passlib/pwdlib, Node argon2/bcrypt, and Elixir argon2_elixir/bcrypt_elixir (as used by phx.gen.auth). Beyond hashing: rate-limit login attempts, check new passwords against breached-password lists (the HIBP k-anonymity API), support passkeys/WebAuthn (Spring Security supports WebAuthn since 6.4), and support MFA (Spring Security 7 added built-in multi-factor support).

Roles and authorities

In Spring Security, everything is a GrantedAuthority (a string). A role is just an authority with the ROLE_ prefix: hasRole("ADMIN") checks for ROLE_ADMIN, while hasAuthority("orders:delete") checks the exact string. JWT scopes become SCOPE_… authorities by default.

Java
// Map custom JWT claims (e.g. Keycloak realm roles) to authorities
@Bean
JwtAuthenticationConverter jwtAuthConverter() {
    var scopes = new JwtGrantedAuthoritiesConverter();                       // "scope" claim → SCOPE_*
    var conv = new JwtAuthenticationConverter();
    conv.setJwtGrantedAuthoritiesConverter(jwt -> {
        Collection<GrantedAuthority> auths = new ArrayList<>(scopes.convert(jwt));
        List<String> roles = jwt.getClaimAsStringList("roles");
        if (roles != null) roles.forEach(r -> auths.add(new SimpleGrantedAuthority("ROLE_" + r)));
        return auths;
    });
    return conv;
}

// Role hierarchy: ADMIN implies USER
@Bean
RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.fromHierarchy("ROLE_ADMIN > ROLE_USER"); }

Design advice: check permissions in code (orders:approve) and map roles to permissions in one place, so business code doesn't encode role names that change with org charts.

Method security

URL rules are coarse. Method security puts authorisation next to the business operation, and can check the resource (ownership):

Java
@Service
class OrderService {
    @PreAuthorize("hasAuthority('SCOPE_orders:read')")
    @PostAuthorize("returnObject.customerId() == authentication.name or hasRole('SUPPORT')")   // ownership check on the result
    public OrderDto find(Long id) { … }

    @PreAuthorize("@orderPolicy.canCancel(authentication, #id)")      // delegate to a bean: testable, readable
    public void cancel(Long id) { … }

    @PostFilter("filterObject.customerId() == authentication.name")    // filters returned collections (beware: loads all first)
    public List<OrderDto> list() { … }
}

@Component("orderPolicy")
class OrderPolicy {
    private final OrderRepository orders;
    OrderPolicy(OrderRepository orders) { this.orders = orders; }
    public boolean canCancel(Authentication auth, Long orderId) {
        return orders.findCustomerId(orderId).map(c -> c.equals(auth.getName())).orElse(false)
            || auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_SUPPORT"));
    }
}

Method security uses AOP proxies (chapter 46): self-invocation bypasses it, and private methods aren't covered. The more robust pattern for ownership is often query-level scoping: findByIdAndCustomerId(id, currentUser) returns nothing for other users' orders, so there's nothing to forget (return 404 rather than 403 so you don't reveal that the order exists). For complex domains, externalise policies (OPA/Rego, Cedar, OpenFGA) and call them from a policy component.

Sessions

Two families of web authentication state:

Server-side sessions (cookie with a session ID) Tokens (bearer JWT or opaque token per request)
State Server stores the session (in memory, Redis via Spring Session, or JDBC) The token carries claims (JWT), or the server introspects it (opaque)
Revocation Instant: delete the session JWT: hard until expiry (keep them short-lived, use deny-lists or rotation); opaque: instant
Browser security HttpOnly cookie, invisible to JS (XSS can't steal it); needs CSRF protection Tokens in JS-accessible storage are stealable by XSS; Authorization headers aren't sent automatically (no CSRF)
Scaling Shared session store needed across instances Stateless validation (JWT signature check)
Best for Browser apps (including the BFF pattern) APIs called by services, mobile apps and BFFs

Session security settings: HttpOnly, Secure, SameSite=Lax (or Strict) cookies; session fixation protection (Spring changes the session ID on login, by default); idle and absolute timeouts; concurrent session control; and invalidation on logout and password change.

CSRF

Cross-Site Request Forgery: a malicious page makes the victim's browser send a request to your site, and the browser automatically attaches cookies, so the request is authenticated as the victim (Vol. 2 ch. 28). Defences:

  • Synchroniser token / double-submit token: a secret token the attacker can't read must accompany state-changing requests (a header or form field). Spring Security enables CSRF protection by default for non-GET requests. For SPAs, use CookieCsrfTokenRepository.withHttpOnlyFalse() plus the X-XSRF-TOKEN header (Angular reads it automatically), or the one-line SPA CSRF configuration in recent Spring Security versions.
  • SameSite cookies (Lax by default in modern browsers) block most cross-site POSTs. They're a strong second layer but not a complete defence on their own (same-site subdomains, older browsers).
  • When can you disable CSRF? Only when no ambient credentials authenticate requests: APIs authenticated purely by Authorization: Bearer headers. If any cookie (session or token-in-cookie) authenticates the request, keep CSRF on.

CORS

CORS relaxes the browser's same-origin policy for specific trusted origins (Vol. 2 ch. 19). It's a browser mechanism: it doesn't protect your API from non-browser clients, and it's not authentication. Configure it at one layer (gateway or application), allow-list exact origins, and never reflect arbitrary Origin headers with Access-Control-Allow-Credentials: true:

Java
@Bean
CorsConfigurationSource corsConfigurationSource() {
    var c = new CorsConfiguration();
    c.setAllowedOrigins(List.of("https://shop.example.com"));          // exact origins, not "*" with credentials
    c.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE"));
    c.setAllowedHeaders(List.of("Authorization", "Content-Type", "Idempotency-Key", "traceparent"));
    c.setExposedHeaders(List.of("Location", "ETag"));
    c.setAllowCredentials(true);
    c.setMaxAge(Duration.ofHours(1));
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", c);
    return source;
}
// .cors(Customizer.withDefaults()) in the filter chain uses this bean, and handles preflights BEFORE authentication.

Modern identity

OAuth 2.0

OAuth 2.0 (RFC 6749, consolidated in the OAuth 2.1 draft) is an authorisation delegation framework: a client application obtains an access token from an authorisation server to call a resource server on behalf of a resource owner (the user), or on its own behalf. The roles:

Role Example
Resource owner The user
Client Your SPA's BFF, mobile app, or a backend service
Authorisation server (AS) Keycloak, Auth0/Okta, Microsoft Entra ID, Google, AWS Cognito, Spring Authorization Server, Ory Hydra, Zitadel
Resource server (RS) Your API, which validates tokens and enforces scopes

Grant types (flows) that matter today:

Grant Who Notes
Authorization Code + PKCE Users via browsers and mobile/native apps The only recommended user-facing flow. The browser is redirected to the AS, the user authenticates, the AS redirects back with a short-lived code, and the client exchanges code + PKCE verifier for tokens
Client Credentials Service-to-service (no user) The client authenticates with its own credentials (secret, private-key JWT, or mTLS) and gets a token for its own identity
Refresh Token Long-lived sessions Exchange for new access tokens. Rotate refresh tokens and detect reuse
Device Authorization TVs, CLIs The user approves on another device
Token Exchange (RFC 8693) Service delegation chains Exchange a user's token for a downstream-scoped one
~~Implicit~~, ~~Resource Owner Password~~ — Deprecated (tokens in URLs; apps handling user passwords)
browser BFF auth server API 1 GET /login 2 302 → AS (challenge, state) 3 /authorize?code_challenge… 4 user logs in 5 302 → /callback?code 6 code 7 code + verifier 8 tokens (kept here) 9 HttpOnly cookie 10 /api + cookie 11 Authorization: Bearer token
Authorization Code flow with PKCE, through a backend-for-frontend. Tokens stay on the server; the browser only holds an HttpOnly session cookie.

PKCE

PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixy") stops an attacker who intercepts the authorisation code (through a malicious app registered for the same redirect scheme, logs, or a referrer leak) from redeeming it:

Interactive diagram: Signing in with OAuth 2.0 and PKCE, through a backend-for-frontend. It needs JavaScript; the text around it says the same.
  1. The client generates a random code_verifier (43–128 characters).
  2. It sends code_challenge = BASE64URL(SHA256(code_verifier)) in the authorisation request.
  3. When exchanging the code, it sends the original code_verifier. The AS hashes it and compares it with the stored challenge.

The attacker has the code but not the verifier, so the exchange fails. PKCE is mandatory for public clients (SPAs, mobile apps with no client secret) and recommended for all clients in OAuth 2.1. The state parameter (CSRF protection for the redirect) and the OIDC nonce (ID-token replay protection) complement it. Spring Security's OAuth2 client handles all three automatically.

OpenID Connect

OAuth 2.0 is about authorisation (access tokens for APIs). It says nothing standard about who the user is. OpenID Connect (OIDC) adds an identity layer on top:

  • The ID token: a JWT for the client, asserting who authenticated (sub, iss, aud, exp, iat, nonce, auth_time, amr, plus profile claims like email and name). It's for the client to learn identity, not to call APIs with.
  • Scopes: openid (required), profile, email, offline_access.
  • A UserInfo endpoint, discovery (/.well-known/openid-configuration lists endpoints, supported algorithms and the JWKS URI with public signing keys), dynamic registration, and logout (RP-initiated, back-channel, front-channel).

"Log in with Google/Microsoft/GitHub" and corporate SSO are OIDC (or SAML, the older XML-based enterprise standard). In Spring Boot, OIDC login is mostly configuration:

YAML
spring.security.oauth2.client:
  registration:
    corp:
      client-id: shop-web
      client-secret: ${OIDC_CLIENT_SECRET}
      scope: openid, profile, email
      authorization-grant-type: authorization_code
  provider:
    corp:
      issuer-uri: https://login.corp.example/realms/shop      # discovery fills in the endpoints and JWKS

JWT

A JSON Web Token (RFC 7519) is a compact, URL-safe token of three Base64URL parts, header.payload.signature:

Text
eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjYtMTAifQ.eyJpc3MiOiJodHRwczovL2xvZ2luLmNvcnAuZXhhbXBsZS9yZWFsbXMvc2hvcCIsInN1YiI6InUtNDIiLCJhdWQiOiJzaG9wLWFwaSIsImV4cCI6MTc5MjgyMDAwMCwic2NvcGUiOiJvcmRlcnM6cmVhZCBvcmRlcnM6d3JpdGUifQ.<signature>

header:  {"alg":"RS256","kid":"2026-10"}                  ← algorithm + key ID (find the key in the issuer's JWKS)
payload: {"iss":"https://login.corp.example/realms/shop","sub":"u-42","aud":"shop-api",
          "exp":1792820000,"scope":"orders:read orders:write"}

Signed (JWS), not encrypted: anyone holding the token can read the payload, so never put secrets or sensitive PII in it (JWE is the encrypted variant, rarely needed). Validation must check:

  1. Signature with the issuer's public key (from the JWKS by kid), using an allow-listed algorithm. Never accept alg: none, and never let the token choose HMAC versus RSA: the classic "algorithm confusion" attack signs with HS256 using the RSA public key as the HMAC secret.
  2. iss equals the expected issuer.
  3. aud contains this API. Otherwise a token minted for another service could be replayed against yours.
  4. exp (and nbf), with small clock skew.
  5. Then authorisation based on scopes/roles and resource ownership.

JWT trade-offs:

  • Stateless verification means no database lookup per request, but revocation is hard: a stolen token works until it expires. Keep access tokens short-lived (5–15 minutes), with refresh-token rotation for sessions. Where instant revocation matters, use opaque tokens with introspection (RFC 7662), or a deny-list keyed by jti.
  • Size: tokens with many claims bloat every request (and can exceed header limits behind proxies).
  • Sender-constrained tokens (DPoP, RFC 9449, or mTLS-bound tokens, RFC 8705) bind a token to a key the client holds, so a stolen token is useless without the private key. They're increasingly used in high-security APIs (FAPI 2.0).
  • Don't build your own sessions out of JWTs in browser apps when a cookie session would do. Use well-tested libraries, never hand-rolled verification.

Resource server

A resource server validates incoming bearer tokens and authorises requests. Spring Boot needs only the issuer:

YAML
spring.security.oauth2.resourceserver.jwt:
  issuer-uri: https://login.corp.example/realms/shop    # discovers the JWKS and validates iss
  audiences: shop-api                                     # validate aud
Java
// Additional validation, e.g. requiring a specific claim
@Bean
JwtDecoder jwtDecoder(OAuth2ResourceServerProperties props) {
    NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation(props.getJwt().getIssuerUri());
    decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer(props.getJwt().getIssuerUri()),
        new JwtClaimValidator<List<String>>("aud", aud -> aud != null && aud.contains("shop-api")),
        new JwtClaimValidator<String>("tenant", t -> t != null && !t.isBlank())));
    return decoder;
}

Keys are fetched from the JWKS and cached. Key rotation works by the AS publishing a new key (a new kid) before signing with it, so resource servers pick it up automatically. Opaque tokens use .oauth2ResourceServer(rs -> rs.opaqueToken(...)) with introspection, which costs a network call per request unless cached.

Authorisation server concepts

The authorisation server is the security-critical centre: user authentication (passwords, passkeys, MFA, federation with social and enterprise IdPs), consent, client registration, token issuance and signing-key management, refresh-token rotation, revocation and introspection, session management and logout, and audit. Don't write one from scratch. Use a product (Keycloak, Okta/Auth0, Entra ID, Cognito, Zitadel, Ory) or a framework like Spring Authorization Server (an OAuth 2.1 and OIDC 1.0 implementation on Spring Security) when you need an embedded, customisable AS, for example machine-to-machine tokens in a closed platform.

Browser apps: the BFF pattern

Where should a browser SPA keep its tokens? Current guidance (the IETF "OAuth 2.0 for Browser-Based Applications" draft) favours the Backend-for-Frontend (BFF): a small server-side component does the OAuth flow as a confidential client, keeps tokens server-side, and gives the browser only an HttpOnly, Secure, SameSite session cookie. The SPA calls the BFF, which attaches the access token and proxies to APIs (Spring Cloud Gateway's TokenRelay filter, or a Spring Boot app with oauth2Login + RestClient and OAuth2AuthorizedClientManager). This keeps tokens away from XSS. CSRF protection is then needed on the BFF, because cookies authenticate. Vol. 2 ch. 28 covers the browser side.

Service-to-service authentication

Inside a platform, services must also authenticate each other. "It's on the internal network" isn't authentication (zero-trust networking, Part X).

Mechanism How Notes
OAuth 2.0 Client Credentials Service A gets a token for itself from the AS (scope=payments:charge) and calls B with Bearer. B validates it as a resource server Standard and auditable. Cache tokens until shortly before expiry (Spring's OAuth2AuthorizedClientManager does). Client authentication should use private-key JWT or mTLS rather than shared secrets
Propagating the user's token A forwards the end user's token to B Simple, but B receives a token with A's audience, and over-broad tokens spread. Prefer token exchange (RFC 8693) to mint a down-scoped token for B on behalf of the user
mTLS (mutual TLS) Both sides present X.509 certificates. The peer's identity comes from the certificate (SPIFFE IDs like spiffe://shop/ns/payments/sa/api) Usually automated by a service mesh (Istio, Linkerd) or SPIFFE/SPIRE, with short-lived certificates rotated automatically. Authenticates the workload, not the user
Cloud workload identity Kubernetes service account tokens federated to cloud IAM (AWS IRSA/EKS Pod Identity, GCP Workload Identity, Azure Workload Identity) No long-lived secrets in pods. The platform issues short-lived credentials
API keys / shared secrets A static key in a header The simplest and weakest option: hard to rotate, often leaked. Acceptable only for low-risk integrations, with rotation and scoping
Signed requests HMAC signatures over method, path, body and timestamp (AWS SigV4-style), often used for webhooks Prevents tampering and replay (with timestamps and nonces). Verify webhook signatures from providers (Stripe, GitHub)
Java
// Client credentials with RestClient: the token is fetched, cached and refreshed automatically
@Bean
RestClient paymentsClient(RestClient.Builder builder, OAuth2AuthorizedClientManager manager) {
    var interceptor = new OAuth2ClientHttpRequestInterceptor(manager);
    interceptor.setClientRegistrationIdResolver(request -> "payments");   // spring.security.oauth2.client.registration.payments.*
    return builder.baseUrl("https://payments.internal").requestInterceptor(interceptor).build();
}

Security in other frameworks

Framework Authentication Authorisation Notes
ASP.NET Core AddAuthentication().AddJwtBearer(...) / .AddCookie() / .AddOpenIdConnect() handlers Policy-based: AddAuthorization(o => o.AddPolicy("CanApprove", p => p.RequireClaim(...))), [Authorize(Policy = …)], IAuthorizationHandler with resource-based checks Antiforgery for CSRF; ASP.NET Core Identity for local users; very similar in spirit to Spring
Go Middleware: coreos/go-oidc for OIDC/JWT verification, golang-jwt/jwt, golang.org/x/oauth2 for clients Explicit checks in handlers or middleware; OPA, Casbin, OpenFGA SDKs Nothing is implicit. Each piece is a small library you compose
Rust (Axum) tower layers or extractors (jsonwebtoken, openidconnect, oauth2 crates); axum-login for sessions Extractors that require a typed principal (AuthUser) make unauthenticated access a compile error in handler signatures Type-driven: a handler taking AdminUser can't be called without it
FastAPI fastapi.security (OAuth2PasswordBearer, HTTPBearer) + Depends(get_current_user); Authlib for OAuth/OIDC Security(get_current_user, scopes=[…]), dependency-based checks OpenAPI documents the security schemes automatically
NestJS Passport strategies (passport-jwt, passport-openidconnect) via AuthGuard Guards (CanActivate), @Roles() decorators + RolesGuard, CASL for ABAC Guards run before interceptors and pipes
Phoenix mix phx.gen.auth generates a complete, secure session-based auth system (Argon2/bcrypt, tokens, email confirmation) into your code; Ueberauth/Assent for OAuth Plugs (require_authenticated_user), policy modules (Bodyguard) Generated code rather than a framework, so it's fully visible and editable

The universal checklist, whatever the stack:

  • deny by default;
  • authenticate at the edge, authorise at the operation and check resource ownership;
  • use proven libraries and identity providers;
  • keep short-lived tokens and validate iss/aud/exp/algorithm;
  • use HttpOnly cookies + CSRF protection for browsers, and bearer tokens for APIs;
  • no secrets in code or tokens;
  • use workload identity for services;
  • audit-log security-relevant actions.

Lab: attacks against authentication, reproduced

Password hashing with Python's bcrypt 5.0 and argon2-cffi 25.1 (and the JDK's PBKDF2 for comparison); JWT verification written by hand to show what libraries must check; CSRF and CORS reproduced in headless Chromium with two sites on one machine: the café at http://localhost:8201 and an attacker's page at http://127.0.0.1:8202 (different hosts, so the browser treats them as different sites and origins). Each browser scenario logs the victim in to the café, then visits the attacker's page.

Experiment 1: how fast can a stolen hash be guessed?

One CPU core, password correct horse battery:

Text
SHA-256 (salted)                           0.0005 ms per hash | 2,209,018 guesses/s per core
PBKDF2-HMAC-SHA256, 600,000 iterations   150.4429 ms per hash |         7 guesses/s per core
bcrypt cost 10                            70.4858 ms per hash |        14 guesses/s per core
bcrypt cost 12                           278.3028 ms per hash |         4 guesses/s per core
Argon2id m=19 MiB, t=2, p=1               29.0346 ms per hash |        34 guesses/s per core

A plain hash allows millions of guesses per second per core, and GPUs do billions: an 8-character password falls in hours. The password-hashing functions slow each guess by a factor of about 100,000 to 300,000. Argon2id with OWASP's minimum parameters was the fastest here for the defender's CPU, but it needs 19 MiB of memory per guess, which is what makes it hard to parallelise on GPUs and custom hardware; that's why OWASP ranks it first. Each cost parameter is a knob you raise over time (bcrypt's cost is logarithmic: 12 is four times 10). The stored hashes carry their parameters and salt, so old hashes keep verifying after you raise the cost and can be re-hashed at the next login:

Text
$2b$10$zLeYL7Rxv/col0e5TW6VPO0r4lifJgaQ/59T.cHPGTFUiIjSkp5AS
$argon2id$v=19$m=19456,t=2,p=1$p+EatdBCBviM/1oOSBWGRA$3OuNtkdzcTrRsnoUmxzVFGUD9PCuy6n39Ncnh6tVwF8
same password, two salts: $2b$10$wu5OfC47.tMdXjcwTU5Swu vs $2b$10$Di8u/zCrU8QeLdrewwB24.

One more detail: bcrypt only uses the first 72 bytes of input. Older libraries silently truncated longer passwords; bcrypt 5.0 now refuses them (ValueError: password cannot be longer than 72 bytes), and Spring Security's BCryptPasswordEncoder also rejects them, so long passphrases need Argon2id or a pre-hash.

Experiment 2: the alg: none token

A forged token with "alg": "none" and an empty signature, claiming admin rights, given to two verifiers:

Text
forged token: eyJhbGciOiAibm9uZSIsICJ0eXAiOiAiSldUIn0.eyJzdWIiOiAibWFsbG9yeSIsICJyb2xlcyI6ICJTVEFGRixBRE1JTiIsICJleHAiOiAxODkzNDU2MDAwfQ.
naive verifier accepts it: {'sub': 'mallory', 'roles': 'STAFF,ADMIN', 'exp': 1893456000}
strict verifier rejects it: unexpected alg none
HS256 token signed with a weak key: key guessed offline from the token alone -> secret

The naive verifier trusted the token's own header to say how it should be verified. This exact flaw affected several JWT libraries in 2015, and its cousin (an RS256 public key accepted as an HS256 secret) still appears in hand-rolled code. The rules: the server fixes the expected algorithm and key; use a maintained library (Spring Security's NimbusJwtDecoder, jose4j, jjwt); validate signature, exp, nbf, iss and aud on every request; and never sign with a guessable secret. An HS256 key can be attacked offline by anyone holding one token, as the last line shows: use at least 256 random bits, or better, asymmetric keys (RS256, ES256, EdDSA) published by the identity provider as a JWKS, so services only ever hold public keys.

Experiment 3: cross-site request forgery and SameSite cookies

The attacker's page contains an auto-submitting form that posts to the café's /orders/cancel-all. The browser decides whether to attach the victim's session cookie:

Text
session cookie SameSite=Lax                       | server saw: POST /orders/cancel-all, no cookie,    Origin http://127.0.0.1:8202 → REJECTED
session cookie SameSite=None; Secure              | server saw: POST /orders/cancel-all, asha-session, Origin http://127.0.0.1:8202 → EXECUTED
SameSite=None, plus a CSRF token check            | server saw: POST /orders/cancel-all, asha-session, Origin http://127.0.0.1:8202 → REJECTED

CSRF works because browsers attach cookies to requests based on where they're going, not where they came from: with SameSite=None the attacker's form carried Asha's session and cancelled her orders. SameSite=Lax (Chrome's default for cookies that don't specify, and what you should set explicitly) stops cookies on cross-site POSTs, so the request arrived anonymous. A CSRF token (a secret value the real site puts in its forms and the attacker can't read) defends even when cookies are sent; Spring Security enables this by default for session-based apps. Checking the Origin header (present on every one of these requests) is a cheap extra layer. APIs authenticated with Authorization: Bearer headers aren't exposed to CSRF at all, because browsers never add that header by themselves; the risk returns the moment tokens are stored in cookies.

Experiment 4: what CORS does and doesn't do

The attacker's script tries to read Asha's profile and to post JSON:

Text
fetch /api/me with credentials, no CORS headers      | server saw: GET /api/me with asha-session | page: BLOCKED TypeError: Failed to fetch
fetch /api/me, CORS allows the attacker's origin     | server saw: GET /api/me with asha-session | page: READ {"user": "asha", "phone": "98xxxxxx21"}
JSON POST, no CORS headers                           | server saw: OPTIONS /api/orders (no cookie)  | page: BLOCKED TypeError: Failed to fetch
JSON POST, CORS allows the attacker's origin         | server saw: OPTIONS, then POST /api/orders with asha-session | page: SENT 201

Two surprises for most developers. First, the "blocked" GET still reached the server with the session cookie: CORS doesn't stop requests, it stops the page from reading responses. A GET with side effects would have run, which is one more reason GET must be safe. Second, the JSON POST triggered a preflight (OPTIONS, sent without cookies) because application/json isn't a "simple" content type; with no CORS approval, the real POST was never sent. Allowing an origin with credentials handed the attacker everything: it could read private data and make authenticated changes. So CORS configuration is an allow-list of trusted front-end origins, never a reflection of whatever Origin arrives, and Access-Control-Allow-Origin: * can't be combined with credentials for exactly this reason.

Try it yourself

  1. Time matches() in the Start here service for a username that exists and one that doesn't. What does the difference let an attacker learn, and how do you fix it (hash a dummy password for unknown users)?
  2. Replace the HS256 signing in Start here with ES256 using KeyPairGenerator.getInstance("EC"), so only the issuer holds the private key.
  3. Change experiment 3's attack to a top-level GET navigation (location = …). Does SameSite=Lax send the cookie now? What does that imply for GET endpoints?
  4. Configure the café's CORS with Spring's CorsConfigurationSource to allow only https://app.cafe.example and verify the preflight responses with curl -X OPTIONS -H 'Origin: …' -H 'Access-Control-Request-Method: POST'.

Revision sheet: Spring Security and modern identity

Key ideas

  • Authentication vs authorisation; 401 (with WWW-Authenticate) vs 403; deny by default; object-level checks (ownership), not just roles (broken access control is OWASP's top risk).
  • Spring Security: SecurityFilterChain beans (ordered, matched by request), AuthenticationManager/providers, SecurityContextHolder, UserDetailsService, PasswordEncoder (delegating, bcrypt default; Argon2id preferred), authorities and roles (ROLE_ prefix), method security (@PreAuthorize), passkeys/WebAuthn (6.4+), MFA (7).
  • Sessions: server-side session plus cookie (HttpOnly, Secure, SameSite); session fixation protection; CSRF tokens for cookie-authenticated state changes.
  • CORS: browsers block reading cross-origin responses unless allowed; preflights for non-simple requests; explicit origin allow-lists; credentials never with *.
  • OAuth 2.0: roles (resource owner, client, authorisation server, resource server); authorisation code flow with PKCE for all clients; client credentials for services; refresh tokens; scopes. Implicit and password grants are deprecated (OAuth 2.1).
  • OpenID Connect: identity layer (ID token, userinfo, discovery, JWKS).
  • JWT: header, payload, signature; validate algorithm (server-chosen), signature, exp/nbf, iss, aud; short lifetimes; asymmetric keys from JWKS; opaque tokens with introspection as the alternative.
  • Browser apps: the BFF pattern keeps tokens server-side, giving the browser only a SameSite session cookie.
  • Service to service: client credentials, mTLS, workload identity (SPIFFE), token exchange.

Numbers to remember

  • Lab: salted SHA-256 about 2.2 million guesses per second per core vs 7 for PBKDF2 at 600,000 iterations, 14 for bcrypt cost 10, 34 for Argon2id (19 MiB).
  • OWASP minimums: Argon2id m=19 MiB, t=2, p=1; PBKDF2-HMAC-SHA256 600,000 iterations; bcrypt cost 10+. bcrypt input limit 72 bytes.

Pitfalls

  • 401/403 confusion; endpoints left public by forgetting a rule (no deny-by-default).
  • Fast hashes, unsalted hashes, encrypted passwords.
  • JWT verification trusting the header's alg; weak HS256 secrets; no aud/iss checks; long-lived tokens without revocation strategy.
  • Tokens in localStorage (readable by any XSS); SameSite=None session cookies without CSRF protection.
  • CORS reflecting any origin with credentials; state-changing GET endpoints.
  • Role checks without ownership checks (IDOR).

Glossary

  • Principal: the authenticated identity.
  • Authority: a granted permission or role.
  • PKCE: proof key for code exchange, binding a code to the client that requested it.
  • ID token: OpenID Connect's token describing the user's authentication.
  • CSRF: tricking a browser into sending authenticated requests from another site.
  • Preflight: the browser's OPTIONS check before a non-simple cross-origin request.