Spring Security for Strong Senior Developers
How does Spring Security's filter chain work and how can you customize it?
Spring Security uses a chain of filters to intercept and process requests before reaching
controllers.
Key filters include:
SecurityContextPersistenceFilter, UsernamePasswordAuthenticationFilter,
ExceptionTranslationFilter, FilterSecurityInterceptor.
Customization options:
Add or remove filters via HttpSecurity or SecurityFilterChain.
Create custom filters by implementing OncePerRequestFilter or GenericFilterBean.
Use DSL to define filter order and access rules.
Filters are ordered to ensure consistent behavior during authentication and
authorization.
How do you implement stateless authentication with JWT in Spring Security?
Stateless authentication avoids server-side sessions; credentials are stored in JWT
tokens.
Implementation steps:
Issue JWT on successful login (with claims, expiry).
Attach token to Authorization header in subsequent requests.
Create a filter to extract, validate, and set Authentication in SecurityContext.
Disable default session creation:
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
Ensure secure signing and validation of JWT (e.g., HMAC, RSA).
How do method-level security annotations like @PreAuthorize and @Secured
work?
@PreAuthorize — evaluates SpEL expressions before method execution.
@Secured — simpler role-based check (e.g., @Secured("ROLE_ADMIN")).
Enable globally via:
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true).
Example:
@PreAuthorize("hasRole('ADMIN') and #id == principal.id")
Useful for enforcing fine-grained security at the service layer.
What is the difference between Authentication and Authorization in Spring
Security?
Authentication — verifying user identity (e.g., login, credentials check).
Authorization — granting access based on roles/permissions.
Authentication sets the Authentication object in SecurityContextHolder.
Authorization uses AccessDecisionManager and voters to decide access rights.
Both are decoupled for flexibility and extensibility.
How would you integrate Spring Security with OAuth2 for single sign-on (SSO)?
Use Spring Security’s OAuth2 client support:
spring-security-oauth2-client (for login via Google, GitHub, etc.).
spring-security-oauth2-resource-server (for JWT and introspection-based
authorization).
Steps:
Configure client registration in application.yml (client-id, client-secret, scopes).
Use @EnableOAuth2Login for browser-based SSO.
Configure WebSecurityConfigurer to allow redirects and token validation.
Customize OAuth2UserService to map external identities to internal roles.