SecurityContext

About

SecurityContext is a core component in Spring Security responsible for storing authentication details of the currently authenticated user. It holds the Authentication object, which contains user credentials, authorities (roles), and additional security-related information.

In a typical Spring Security flow, SecurityContext is populated once a user is authenticated and remains accessible throughout the request lifecycle.

Why is SecurityContext Important?

  • Stores user authentication details securely.

  • Provides access to authenticated user information in any part of the application.

  • Ensures thread-local storage, allowing seamless access to authentication data within the same thread.

  • Plays a key role in method-level security, allowing role-based authorization.

SecurityContext Interface

The SecurityContext interface is defined as follows:

public interface SecurityContext extends Serializable {
    Authentication getAuthentication();
    void setAuthentication(Authentication authentication);
}

Method

Purpose

getAuthentication()

Retrieves the current Authentication object.

setAuthentication(Authentication authentication)

Updates the authentication details in the context.

Default Implementation

Spring Security provides the SecurityContextImpl class as the default implementation of SecurityContext.

public class SecurityContextImpl implements SecurityContext {
    private Authentication authentication;

    public SecurityContextImpl() {}

    public SecurityContextImpl(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public String toString() {
        return this.authentication == null ? "Empty SecurityContext" : "Authentication=" + this.authentication;
    }
}

How to Access SecurityContext in Spring Applications

Spring provides SecurityContextHolder to retrieve authentication details.

@GetMapping("/user-info")
public ResponseEntity<String> getUserInfo() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    return ResponseEntity.ok("Authenticated User: " + username);
}
  • Retrieves the currently logged-in user's username.

  • authentication.getAuthorities() can be used to fetch roles/permissions.

Last updated

Was this helpful?