Section 9 Spring Security True Senior H1 H2
Section 9 Spring Security True Senior H1 H2
Spring Security
How does Spring Security handle authentication and what is the role of the
SecurityContext?
Spring Security uses AuthenticationManager to validate credentials and produce an
Authentication object.
The authenticated principal is stored in a thread-local SecurityContext during the
request lifecycle.
SecurityContext is propagated using filters and cleared after request processing
completes.
In multi-threaded or async environments, the context must be manually propagated or
managed via DelegatingSecurityContextExecutor.
Improper context handling can result in loss of security state and unauthorized access.
How do you configure method-level security and what are common pitfalls?
Enable @EnableGlobalMethodSecurity with prePostEnabled or securedEnabled as
needed.
Use annotations like @PreAuthorize, @PostAuthorize, and @Secured for fine-grained
access control.
SpEL expressions allow dynamic checks on roles, parameters, or return values.
Method security applies only if method is called through a proxy — self-invocation
bypasses security.
Complex expressions can be hard to test and debug — prefer service-level access
encapsulation.
What are the key considerations when using JWT for authentication in Spring
Security?
Use strong asymmetric encryption (RSA/ECDSA) for token signing and avoid storing
secrets client-side.
Validate token expiration, audience, issuer, and signature on every request.
Avoid putting sensitive information in token claims — tokens are base64-encoded, not
encrypted.
Rotate keys periodically and provide a revocation strategy (e.g., blacklist, token
versioning).
Use short-lived access tokens with refresh token support via secure endpoints.
How does Spring Security’s filter chain work and how do you customize it?
Security filters are applied in a strict order defined by FilterChainProxy.
Filters like UsernamePasswordAuthenticationFilter, BasicAuthenticationFilter, and
others handle specific stages.
Custom filters must be added before/after specific built-in filters to ensure proper
behavior.
Filter order matters for security — misplacing filters can lead to vulnerabilities or
bypasses.
Always test full filter chain interaction when adding custom logic (e.g., logging, CORS,
audit).
How would you secure REST APIs differently from form-based applications?
REST APIs use stateless authentication (e.g., JWT, API Keys) and avoid CSRF tokens.
Disable session creation and CSRF protection in REST-specific security configurations.
Return HTTP status codes (401/403) instead of redirecting to login forms.
Expose authentication/authorization failures as standardized JSON responses.
Validate content types, rate limit endpoints, and log failed access attempts.
What are some best practices for securely storing and validating user
credentials?
Use BCrypt or Argon2 hashing algorithms for password encoding, never plain-text or
MD5/SHA1.
Use a strong salt and configure work factor (e.g., BCrypt strength = 10+).
Limit failed login attempts and implement account lockout policies.
Store credentials in secure, encrypted databases and never log passwords.
Validate credentials via AuthenticationManager and never implement custom logic
directly.
How would you implement role-based access control (RBAC) in Spring Security?
Define roles as authorities (e.g., ROLE_ADMIN) and map them to user entities.
Use @PreAuthorize or hasRole('ROLE_XXX') in controller/service layer for enforcement.
Store role hierarchies or permission matrices in database or central policy service.
Use PermissionEvaluator or AccessDecisionManager for fine-grained domain-level
access.
Ensure role checks align with business rules and are unit tested in isolation.
How do you test Spring Security configurations and custom authorization logic?
Use @WithMockUser and @WithUserDetails for mocking security contexts in unit tests.
Test controller endpoints with MockMvc and security filters in place.
Write integration tests that simulate full authentication flow including tokens or
sessions.
Mock Authentication/Principal objects in service-level unit tests.
Cover both success and failure scenarios — unauthorized, forbidden, and edge cases.