Spring Security is built on several fundamental principles that form the backbone of its architecture and functionality. Understanding these principles is crucial for implementing robust security solutions.
Authentication vs Authorization
Authentication answers “Who are you?” while Authorization answers “What can you do?” Spring Security treats these as separate concerns, allowing for flexible security configurations.
Spring Security operates through a chain of filters that intercept HTTP requests. Each filter has a specific responsibility and can either process the request or pass it to the next filter.
flowchart TD
A[HTTP Request] --> B[Security Filter Chain]
B --> C[SecurityContextPersistenceFilter]
C --> D[UsernamePasswordAuthenticationFilter]
D --> E[ExceptionTranslationFilter]
E --> F[FilterSecurityInterceptor]
F --> G[Application Controller]
style B fill:#e1f5fe
style G fill:#e8f5e8
SecurityContext and SecurityContextHolder
The SecurityContext stores security information for the current thread of execution. The SecurityContextHolder provides access to this context.
1 2 3 4 5 6 7 8 9
// Getting current authenticated user Authenticationauthentication= SecurityContextHolder.getContext().getAuthentication(); Stringusername= authentication.getName(); Collection<? extendsGrantedAuthority> authorities = authentication.getAuthorities();
Interview Insight: “How does Spring Security maintain security context across requests?”
Spring Security uses ThreadLocal to store security context, ensuring thread safety. The SecurityContextPersistenceFilter loads the context from HttpSession at the beginning of each request and clears it at the end.
Principle of Least Privilege
Spring Security encourages granting minimal necessary permissions. This is implemented through role-based and method-level security.
1 2 3 4
@PreAuthorize("hasRole('ADMIN') or (hasRole('USER') and #username == authentication.name)") public User getUserDetails(@PathVariable String username) { return userService.findByUsername(username); }
When to Use Spring Security Framework
Enterprise Applications
Spring Security is ideal for enterprise applications requiring:
sequenceDiagram
participant U as User
participant B as Browser
participant S as Spring Security
participant A as AuthenticationManager
participant P as AuthenticationProvider
participant D as UserDetailsService
U->>B: Enter credentials
B->>S: POST /login
S->>A: Authenticate request
A->>P: Delegate authentication
P->>D: Load user details
D-->>P: Return UserDetails
P-->>A: Authentication result
A-->>S: Authenticated user
S->>B: Redirect to success URL
B->>U: Display protected resource
@Bean public HttpSessionEventPublisher httpSessionEventPublisher() { returnnewHttpSessionEventPublisher(); }
@Bean public SessionRegistry sessionRegistry() { returnnewSessionRegistryImpl(); }
Interview Insight: “How does Spring Security handle concurrent sessions?”
Spring Security can limit concurrent sessions per user through SessionRegistry. When maximum sessions are exceeded, it can either prevent new logins or invalidate existing sessions based on configuration.
Session Timeout Configuration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// In application.properties server.servlet.session.timeout=30m
@Service publicclassDocumentService { @PreAuthorize("hasRole('ADMIN')") publicvoiddeleteDocument(Long documentId) { // Only admins can delete documents } @PreAuthorize("hasRole('USER') and #document.owner == authentication.name") publicvoideditDocument(@P("document") Document document) { // Users can only edit their own documents } @PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')") public Document getDocument(Long documentId) { return documentRepository.findById(documentId); } @PreFilter("filterObject.owner == authentication.name") publicvoidprocessDocuments(List<Document> documents) { // Process only documents owned by the current user } }
Interview Insight: “What’s the difference between @PreAuthorize and @Secured?”
@PreAuthorize supports SpEL expressions for complex authorization logic, while @Secured only supports role-based authorization. @PreAuthorize is more flexible and powerful.
// WRONG: Ordering matters in security configuration http.authorizeRequests() .anyRequest().authenticated() // This catches everything .antMatchers("/public/**").permitAll(); // This never gets reached
// CORRECT: Specific patterns first http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated();
Interview Insight: “What happens when Spring Security configuration conflicts occur?”
Spring Security evaluates rules in order. The first matching rule wins, so specific patterns must come before general ones. Always place more restrictive rules before less restrictive ones.
Q: Explain the difference between authentication and authorization in Spring Security. A: Authentication verifies identity (“who are you?”) while authorization determines permissions (“what can you do?”). Spring Security separates these concerns - AuthenticationManager handles authentication, while AccessDecisionManager handles authorization decisions.
Q: How does Spring Security handle stateless authentication? A: For stateless authentication, Spring Security doesn’t maintain session state. Instead, it uses tokens (like JWT) passed with each request. Configure with SessionCreationPolicy.STATELESS and implement token-based filters.
Q: What is the purpose of SecurityContextHolder? A: SecurityContextHolder provides access to the SecurityContext, which stores authentication information for the current thread. It uses ThreadLocal to ensure thread safety and provides three strategies: ThreadLocal (default), InheritableThreadLocal, and Global.
Q: How do you implement custom authentication in Spring Security? A: Implement custom authentication by:
Creating a custom AuthenticationProvider
Implementing authenticate() method
Registering the provider with AuthenticationManager
Optionally creating custom Authentication tokens
Practical Implementation Questions
Q: How would you secure a REST API with JWT tokens? A: Implement JWT security by:
Creating JWT utility class for token generation/validation
Implementing JwtAuthenticationEntryPoint for unauthorized access
Creating JwtRequestFilter to validate tokens
Configuring HttpSecurity with stateless session management
Adding JWT filter before UsernamePasswordAuthenticationFilter
Q: What are the security implications of CSRF and how does Spring Security handle it? A: CSRF attacks trick users into performing unwanted actions. Spring Security provides CSRF protection by:
Generating unique tokens for each session
Validating tokens on state-changing requests
Storing tokens in HttpSession or cookies
Automatically including tokens in forms via Thymeleaf integration
Spring Security provides a comprehensive, flexible framework for securing Java applications. Its architecture based on filters, authentication managers, and security contexts allows for sophisticated security implementations while maintaining clean separation of concerns. Success with Spring Security requires understanding its core principles, proper configuration, and adherence to security best practices.
The framework’s strength lies in its ability to handle complex security requirements while providing sensible defaults for common use cases. Whether building traditional web applications or modern microservices, Spring Security offers the tools and flexibility needed to implement robust security solutions.