JWT Authentication in Spring Boot
Most Spring Boot APIs authenticate with JWT bearer tokens, either issued by an identity provider such as Keycloak, Auth0 or Cognito, or by the app itself. Interviewers ask how tokens are validated, how roles map to authorities, and how refresh and logout work.
What you will learn
- Configure a JWT resource server with an issuer
- Map token claims to Spring authorities
- Know the trade-offs of issuing your own tokens
- Handle refresh tokens and revocation
Key concepts
Resource server
spring-boot-starter-oauth2-resource-server validates the token signature with the issuer's public keys (JWKS), checks exp, nbf and iss, and builds a JwtAuthenticationToken.
Authorities from claims
By default the scope claim becomes SCOPE_ authorities. Map a roles claim to ROLE_ authorities with a JwtAuthenticationConverter.
Short-lived access tokens
Access tokens expire in minutes; clients use a refresh token (kept server-side or in an HttpOnly cookie) to get new ones. Revoke by deleting the refresh token.
Step by step
Configuration
# application.yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.example.com/realms/jiocoder
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
var roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles");
roles.setAuthorityPrefix("ROLE_");
var converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
return converter;
}Examples
Reading the user in a controller
@GetMapping("/api/me")
MeResponse me(@AuthenticationPrincipal Jwt jwt) {
return new MeResponse(jwt.getSubject(), jwt.getClaimAsString("email"));
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Run Keycloak in Docker, create a realm and protect an endpoint with a role.
- Write a test with SecurityMockMvcRequestPostProcessors.jwt() that checks a 403 for a missing role.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Should you write your own JWT filter?
Usually not. Spring Security's resource server already validates signatures, expiry, issuer and audience correctly. A hand-written OncePerRequestFilter is easy to get wrong (no algorithm pinning, no audience check). Write one only for special cases.
How do you log a user out with JWTs?
Delete or revoke the refresh token so no new access tokens are issued, clear the cookie, and accept that the current access token works until it expires in a few minutes, or keep a short-lived deny-list of token ids for immediate revocation.
Summary
Use Spring's OAuth2 resource server to validate JWTs from your issuer, map claims to authorities with a converter, keep access tokens short-lived, and revoke through refresh tokens.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus