Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

Spring Security forgets the login and treats the next request as anonymous

Your error

Did not find SecurityContext in HttpSession <session-id> using the SPRING_SECURITY_CONTEXT session attribute2 more lines it can show

Fix it fast

Most common cause, 1 of 3

A custom login endpoint sets the context but never saves it

Save the new context through a SecurityContextRepository in the same request that authenticates the user.

Fix
private final SecurityContextRepository securityContextRepository =
        new HttpSessionSecurityContextRepository();
private final SecurityContextHolderStrategy securityContextHolderStrategy =
        SecurityContextHolder.getContextHolderStrategy();

@PostMapping("/login")
public void login(@RequestBody LoginRequest body,
                  HttpServletRequest request, HttpServletResponse response) {
    var token = UsernamePasswordAuthenticationToken.unauthenticated(body.getUsername(), body.getPassword());
    Authentication authentication = authenticationManager.authenticate(token);
    SecurityContext context = securityContextHolderStrategy.createEmptyContext();
    context.setAuthentication(authentication);
    securityContextHolderStrategy.setContext(context);
    securityContextRepository.saveContext(context, request, response);
}
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

Did not find SecurityContext in HttpSession means the login worked on one request but was never stored, so the next request runs as anonymous and gets 403. Since Spring Security 6, a custom login controller or filter must call securityContextRepository.saveContext(); STATELESS session policy stores nothing at all. Applies to Spring Security 6.5 and 7.x.

  • Applies to Spring Security 7.2.0, Spring Security 6.5.x, Spring Boot with logging.level.org.springframework.security=TRACE
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Turn on Spring Security's TRACE logging, log in, then call a protected URL and read the lines for that second request. Did not find SecurityContext in HttpSession points to cause 1, no HttpSession lines at all with a STATELESS policy points to cause 2, and No HttpSession currently exists points to cause 3.

Run this first
# application.properties
logging.level.org.springframework.security=TRACE

Then find the line you see in this list and open its fix:

  1. 1A custom login endpoint sets the context but never saves itThe second request logs Did not find SecurityContext in HttpSession with a real session id
  2. 2The filter chain is STATELESS, so nothing is stored between requestsThe configuration has SessionCreationPolicy.STATELESS and the log never mentions an HttpSession
  3. 3The browser never sends the session cookie backThe request after login logs No HttpSession currently exists, often from a front end on another origin

What does the error look like?

  • Did not find SecurityContext in HttpSession <session-id> using the SPRING_SECURITY_CONTEXT session attribute
  • No HttpSession currently exists
  • Set SecurityContextHolder to anonymous SecurityContext

Cause 1 of 3

A custom login endpoint sets the context but never saves it

You seeThe second request logs Did not find SecurityContext in HttpSession with a real session id

Check

Did not find SecurityContext in HttpSession after a successful custom login means the Authentication only lived in the SecurityContextHolder for that one request. In Spring Security 6 and later, SecurityContextHolderFilter loads the context but does not save it, so code that authenticates in its own controller or filter has to write it to the SecurityContextRepository itself.

Check
grep -rn "SecurityContextHolder\|saveContext" src/main/java

Fix

Save the new context through a SecurityContextRepository in the same request that authenticates the user. The reference docs show this pattern for a REST login controller; HttpSessionSecurityContextRepository stores it in the session for later requests.

Fix
private final SecurityContextRepository securityContextRepository =
        new HttpSessionSecurityContextRepository();
private final SecurityContextHolderStrategy securityContextHolderStrategy =
        SecurityContextHolder.getContextHolderStrategy();

@PostMapping("/login")
public void login(@RequestBody LoginRequest body,
                  HttpServletRequest request, HttpServletResponse response) {
    var token = UsernamePasswordAuthenticationToken.unauthenticated(body.getUsername(), body.getPassword());
    Authentication authentication = authenticationManager.authenticate(token);
    SecurityContext context = securityContextHolderStrategy.createEmptyContext();
    context.setAuthentication(authentication);
    securityContextHolderStrategy.setContext(context);
    securityContextRepository.saveContext(context, request, response);
}

Verify

On the next request the TRACE log shows Retrieved followed by your user's authentication instead of the anonymous context.

Verify
curl -i -c jar.txt -X POST -H 'Content-Type: application/json' -d '{"username":"u","password":"p"}' http://localhost:8080/login && curl -i -b jar.txt http://localhost:8080/api/me

Confirmed by docs.spring.io

Did this fix it?

Cause 2 of 3

The filter chain is STATELESS, so nothing is stored between requests

You seeThe configuration has SessionCreationPolicy.STATELESS and the log never mentions an HttpSession

Check

Here the session lookup does not even happen. Spring's docs explain that SessionCreationPolicy.STATELESS switches the SecurityContextRepository to NullSecurityContextRepository, which saves nothing, so a login on one call cannot carry over to the next one.

Check
grep -rn "SessionCreationPolicy" src/main/java

Fix

Choose one model. For a browser login kept in the session, remove STATELESS (or use IF_REQUIRED) and save the context as in cause 1. For a token API, keep STATELESS and authenticate every request with the token, for example an Authorization header read by your filter.

Fix
http
    // session-based login
    .sessionManagement((session) -> session
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));

Verify

After logging in, the TRACE log for the next request retrieves the stored context, or, for a token API, each request authenticates from its own header.

Verify
curl -i -b jar.txt http://localhost:8080/api/me

Confirmed by docs.spring.io

Did this fix it?

Cause 3 of 3

The browser never sends the session cookie back

You seeThe request after login logs No HttpSession currently exists, often from a front end on another origin

Check

No HttpSession currently exists means the request arrived without the JSESSIONID cookie, so Spring had no session to read. A cross-origin fetch sends cookies only with credentials set to include, and the browser also needs Access-Control-Allow-Credentials plus an exact origin, not *, in the response.

Check
curl -i -X POST http://localhost:8080/login | grep -i set-cookie

Fix

Send cookies from the front end and allow credentials for that exact origin in the CORS configuration that Spring Security uses.

Fix
// front end
fetch("https://api.example.com/api/me", { credentials: "include" });

// Spring Security CORS source
@Bean
UrlBasedCorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(List.of("https://app.example.com"));
    configuration.setAllowedMethods(List.of("GET", "POST"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Verify

In the browser's network tab, the request after login carries the JSESSIONID cookie and the response is 200.

Verify
curl -i -b jar.txt -H 'Origin: https://app.example.com' http://localhost:8080/api/me

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Prefer Spring Security's own formLogin or a filter that extends its authentication filters, which save the context for you, over a hand-written login controller.
  • Add an integration test that logs in and then calls a protected endpoint with the returned cookie, so a missing saveContext call fails in CI.
  • Decide per filter chain whether it is session-based or token-based, and never mix STATELESS with a login that expects a session.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: Dispatch Pro.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.