How to Validate JWT Token in Spring Boot Securely
To validate a
JWT token in Spring Boot, parse the token using a JWT library like jjwt with your secret key and check its claims and expiration. Typically, this is done inside a filter or interceptor that extracts the token from the Authorization header and verifies its signature and validity before allowing access.Syntax
Use the io.jsonwebtoken.Jwts parser to validate a JWT token by providing the secret key. The main steps are:
- Extract the token string from the HTTP request header.
- Parse the token with the secret key to verify signature and claims.
- Handle exceptions for invalid or expired tokens.
java
Claims claims = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();Example
This example shows a Spring Boot filter that extracts the JWT token from the Authorization header, validates it using the jjwt library, and sets authentication if valid.
java
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpFilter; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.authority.SimpleGrantedAuthority; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.Key; import java.util.List; public class JwtTokenFilter extends HttpFilter { private final Key secretKey = Keys.hmacShaKeyFor("mysecretkeymysecretkeymysecretkey12".getBytes(StandardCharsets.UTF_8)); @Override protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { String token = header.substring(7); try { Claims claims = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) .getBody(); String username = claims.getSubject(); if (username != null) { var auth = new UsernamePasswordAuthenticationToken( username, null, List.of(new SimpleGrantedAuthority("ROLE_USER")) ); SecurityContextHolder.getContext().setAuthentication(auth); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } chain.doFilter(request, response); } }
Output
When a request with a valid JWT token in the Authorization header is sent, the filter sets the user authentication in the security context allowing access; invalid or missing tokens result in 401 Unauthorized response.
Common Pitfalls
- Not verifying the token signature with the correct secret key causes invalid tokens to pass.
- Ignoring token expiration allows old tokens to be accepted.
- Failing to extract the token properly from the
Authorizationheader (missing "Bearer " prefix). - Not handling exceptions from the JWT parser leads to server errors instead of proper 401 responses.
java
/* Wrong: Not checking 'Bearer ' prefix and ignoring exceptions */ String token = request.getHeader("Authorization"); Claims claims = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) // token may be null or malformed .getBody(); /* Right: Check prefix and catch exceptions */ String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { String token = header.substring(7); try { Claims claims = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) .getBody(); // proceed } catch (Exception e) { // handle invalid token } }
Quick Reference
Remember these key points when validating JWT tokens in Spring Boot:
- Always extract token from
Authorizationheader with "Bearer " prefix. - Use
jjwtparser with your secret key to verify signature and claims. - Check token expiration and handle exceptions gracefully.
- Set authentication in Spring Security context if token is valid.
Key Takeaways
Extract the JWT token from the Authorization header starting with 'Bearer '.
Use the jjwt library's parser with your secret key to validate the token signature and claims.
Always handle exceptions to reject invalid or expired tokens with a 401 response.
Set the authenticated user in Spring Security context after successful validation.
Never trust tokens without verifying signature and expiration.