Spring Security Context

Spring Security Context
The SecurityContext in Spring Security holds the authentication and security-related details (like the logged-in user, roles, etc.) for the current thread of execution. It’s stored in a ThreadLocal, so each request has its own context.

Example:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@RestController
public class UserController {

    @GetMapping("/me")
    public String getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return "Logged in as: " + auth.getName();
    }
}

Key Point:
SecurityContextHolderSecurityContextAuthenticationPrincipal (UserDetails)

Leave a Reply