0% found this document useful (0 votes)
12 views3 pages

Section 9 Spring Security True Senior H1 H2

Spring Security handles authentication using AuthenticationManager and stores the authenticated principal in a thread-local SecurityContext. It differentiates between stateless and stateful authentication, with stateless relying on tokens and stateful maintaining server-side sessions. Key considerations for implementing security include method-level security configuration, multi-tenant authentication, JWT usage, REST API security, credential storage, role-based access control, and testing security configurations.

Uploaded by

pbecic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Section 9 Spring Security True Senior H1 H2

Spring Security handles authentication using AuthenticationManager and stores the authenticated principal in a thread-local SecurityContext. It differentiates between stateless and stateful authentication, with stateless relying on tokens and stateful maintaining server-side sessions. Key considerations for implementing security include method-level security configuration, multi-tenant authentication, JWT usage, REST API security, credential storage, role-based access control, and testing security configurations.

Uploaded by

pbecic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

9.

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.

What are the differences between stateless and stateful authentication in


Spring Security?
 Stateless authentication uses tokens (e.g., JWT) and avoids server-side session storage.
 Stateful authentication maintains user sessions on the server (e.g., HttpSession) with
session IDs.
 Stateless auth is easier to scale horizontally but requires client-side token handling and
rotation.
 Stateful sessions offer tighter control over session invalidation and fine-grained timeout
policies.
 Choose based on system size, client trust, and infrastructure capabilities.

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.

How would you implement multi-tenant authentication and authorization in


Spring Security?
 Store tenant context in a thread-local or request-scoped bean extracted from headers or
subdomain.
 Customize UserDetailsService or AuthenticationProvider to validate tenant-bound
credentials.
 Scope roles and authorities per tenant using custom PermissionEvaluator or access
decision logic.
 Include tenant ID in JWT claims and validate token against tenant registry or
boundaries.
 Isolate security config per tenant when using SaaS-style multitenancy or tenant-aware
filters.

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.

You might also like