🔐 1. How does Spring Security integrate with JWT-based authentication?
Answer:
Spring Security provides a flexible filter chain where you can plug in your own OncePerRequestFilter (e.g., JwtAuthenticationFilter) to intercept incoming requests and:
Extract the JWT from the Authorization header
Validate it
Set the Authentication object in SecurityContextHolder
➡️ This allows stateless authentication using JWT.
🔐 2. Why do we use OncePerRequestFilter in JWT security setup?
Answer:
OncePerRequestFilter ensures your filter runs only once per request, making it ideal for:
Checking JWT
Verifying token signature
Setting authentication context
If used wrongly, it can cause repeated token processing.
🔐 3. Can we disable session creation in Spring Security for JWT?
Answer:
Yes. JWT is stateless, so we must disable session creation:
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
Without this, Spring may still create sessions and defeat the purpose of using JWT.
🔐 4. Where do you validate the JWT token in Spring Boot?
Answer:
In a custom JWT filter, before the request reaches the controller:
You extract the token from Authorization header
Validate the signature and expiration
Fetch user details (optional)
Set Authentication in SecurityContext
🔐 5. What happens if the JWT token is expired?
Answer:
When a JWT token is expired, it throws a specific exception — most commonly:
io.jsonwebtoken.ExpiredJwtException
In your custom JWT filter (usually extending OncePerRequestFilter), you should catch this exception and return a proper HTTP response:
try {
// validate token logic
} catch (ExpiredJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Token expired. Please login again or use refresh token.");
return;
}
📌 HTTP Response:
401 Unauthorized
Body: Token expired. Please login again or use refresh token.
🔄 Best Practice: Use a refresh token mechanism so that expired tokens can be refreshed without forcing the user to re-login every time.
🔐 6. How do you handle JWT in microservices architecture with Spring Security?
Answer:
In microservices, the best approach is to delegate all authentication to a central Auth Service. Here's the flow:
User logs in via Auth Service → receives access token and refresh token.
Access token is then passed in the Authorization: Bearer <token> header for every request to other services.
Each service:
Validates the token using a shared secret or public key (if using asymmetric signing like RS256).
Authorizes the request based on roles in token claims.
No session state is stored; each service is stateless.
✨ Optional best practice:
Use Spring Cloud Gateway or an API Gateway to centralize token validation so individual services don't have to repeat it.
🔐 7. Is it safe to keep user roles in JWT?
Answer:
Yes — if the JWT is signed properly using a secure algorithm (HS256, RS256) and a strong secret/private key.
You can embed roles in the JWT payload like this:
{
"sub": "user1",
"roles": ["ROLE_ADMIN", "ROLE_USER"],
"exp": 1723489234
}
📌 In your Spring Boot filter, you extract these roles and convert them to GrantedAuthority:
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
username, null, authoritiesFromToken
);
⚠️ Do not trust claims blindly if the signature is invalid or token is tampered.
✅ Signed tokens = safe to use for roles
❌ Unsigned (alg: none) or weak key = huge security risk
🔐 8. What is the best way to store JWT tokens on the frontend?
Answer:
Access token: HttpOnly Secure Cookie (to avoid XSS)
Refresh token: also in HttpOnly cookie or encrypted local storage
❌ Avoid storing in localStorage or sessionStorage — vulnerable to XSS attacks.
🔐 9. Can we use Spring Security with both Session and JWT?
Answer:
Not advisable. Choose one:
Use Session + CSRF for monoliths or UI-driven apps
Use JWT (stateless) for REST APIs and microservices
Mixing both often leads to confusion and security holes.
🔐 10. How do you implement role-based access with JWT + Spring Security?
Answer:
Encode roles into JWT claims.
In your filter, extract and set GrantedAuthority in Authentication.
Then use:
@PreAuthorize("hasRole('ADMIN')")
or
http.authorizeHttpRequests().requestMatchers("/admin/**").hasRole("ADMIN")
✅ Don’t forget to prefix roles with "ROLE_".
No comments:
Post a Comment