Explain SecurityContext and SecurityContext Holder in Spring security.

SecurityContext holds the authentication details of the currently logged-in user, and SecurityContextHolder is the static access point that stores and retrieves that SecurityContext for the duration of a request.

Key Points: • SecurityContext wraps the Authentication object, which includes the principal, credentials, and granted authorities. • SecurityContextHolder uses a ThreadLocal by default, so the context is automatically scoped to the current request's thread. • Any code in the call stack can retrieve the current user via SecurityContextHolder.getContext().getAuthentication() without it being passed explicitly as a parameter. • Spring Security's filter chain populates the SecurityContext after successful authentication and clears it at the end of the request. • Strategy modes (MODE_THREADLOCAL, MODE_INHERITABLETHREADLOCAL, MODE_GLOBAL) control how context propagates across threads, relevant for async processing.

Example: Inside a service method, calling SecurityContextHolder.getContext().getAuthentication().getName() returns the currently logged-in username without needing it passed down from the controller.

Code Example:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String currentUsername = auth.getName();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();

Interview Tip: A concise interview answer is:

"SecurityContext holds the current user's Authentication—their principal, credentials, and authorities—while SecurityContextHolder is the static, thread-local access point Spring Security uses to store and retrieve that context. It's how any code in the request can access the current user without it being explicitly passed around."