Spring-boot读书笔记一SecurityContextHolder
SecurityContextHolder is a core Spring Security class that provides access to the security context of the current thread.
Key Concepts
Purpose: Central access point for security information in Spring Security applications
Thread Association: Associates security context with the current executing thread
Core Methods
Getting Security Context:
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
Direct Authentication Access:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Storage Strategies
SecurityContextHolder uses different strategies to store the security context:
- MODE_THREADLOCAL (default): Stores context in ThreadLocal
- MODE_INHERITABLETHREADLOCAL: Context inherited by child threads
- MODE_GLOBAL: Single global context for entire JVM
Authentication Object
The Authentication object retrieved contains:
- Principal: Usually the username or user object
- Credentials: Usually the password (often cleared after authentication)
- Authorities: Collection of granted authorities/roles
- Details: Additional authentication details
Usage in the Code
In the CustomAccessDeniedHandler:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
This retrieves the current user's authentication information to log who attempted unauthorized access.
Important Notes
- Returns null if no authentication exists
- Context is automatically populated by Spring Security filters
- Thread-safe when using default ThreadLocal strategy
- Cleared automatically at the end of request processing

浙公网安备 33010602011771号