Spring Security: Authentication returns anonynmous user after login. How to fix it?

Issue

After a successful login in a Spring Boot application using Spring Security, the SecurityContext still contains an anonymous user instead of the authenticated user.

Everytime I try to call SecurityContextHolder.getContext().getAuthentication().getPrincipal(), it returns anonymousUser or null. Same thing when I try with the annotation @AuthenticationPrincipal

Also the endpoints with required authentication return 403 Forbidden. How can I fix this?

Solution

You can try the following steps to fix this:

1. Ensure SecurityContextPersistenceFilter is applied

Spring Security maintains authentication state using SecurityContextPersistenceFilter. If this filter is missing or overridden incorrectly, the user session won’t persist.

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/secure/**").authenticated()
            .anyRequest().permitAll()
        )
        .formLogin(withDefaults())
        .securityContext(security -> security.securityContextRepository(new HttpSessionSecurityContextRepository()));
    return http.build();
}

This ensures that authentication is stored in the session and persists across requests.

2. Ensure the Custom Authentication Provider is Setting Authentication

If you’re using a custom authentication provider, ensure it properly sets authentication:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();
    UserDetails user = userDetailsService.loadUserByUsername(username);
    return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
}

Ensure that the authentication object is set in SecurityContextHolder:

SecurityContextHolder.getContext().setAuthentication(authentication);

3. Verify Filters Execution Order

Spring Security applies filters in a specific order. If a custom filter runs before authentication, the SecurityContext might not update properly. Check logs to ensure that authentication happens before the request reaches secured endpoints.