Back to Garden
Engineering|August 14, 2025

Using JSON Web Tokens (JWT) with Spring Boot for Authentication and Authorization

#SpringBoot#Security

Learn how to use JSON Web Tokens (JWT) with Spring Boot for authentication and authorization. Spring Boot provides excellent support for…

Learn how to use JSON Web Tokens (JWT) with Spring Boot for authentication and authorization. Spring Boot provides excellent support for JWT and makes it easy to use in your applications. In this article, I will show you how to configure and use JWT with Spring Boot.

First, let’s look at the dependency that we need to include in our pom.xml to use JWT with Spring Boot:

<dependency>  
    <groupId>io.jsonwebtoken</groupId>  
    <artifactId>jjwt</artifactId>  
    <version>0.7.0</version>  
</dependency>

To use JWT with Spring Boot, we first need to configure some basic things such as the secret key that will be used for signing the JWT tokens and the token expiration time. We can do this by creating a class that extends WebSecurityConfigurerAdapter and adding the following configuration:

@EnableWebSecurity  
public class SecurityConfig extends WebSecurityConfigurerAdapter {  
  
    @Value("${jwt.secret}")  
    private String secretKey;  
  
    @Value("${jwt.expiration}")  
    private long tokenExpiration;  
  
    @Bean  
    public JwtTokenProvider jwtTokenProvider() {  
        return new JwtTokenProvider(secretKey, tokenExpiration);  
    }  
  
    @Override  
    protected void configure(HttpSecurity http) throws Exception {  
        http  
            .cors()  
            .and()  
            .csrf()  
            .disable()  
            .sessionManagement()  
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)  
            .and()  
            .authorizeRequests()  
            .antMatchers("/login")  
            .permitAll()  
            .anyRequest()  
            .authenticated()  
            .and()  
            .apply(new JwtTokenFilterConfigurer(jwtTokenProvider()));  
    }  
}

Next, let’s create a JwtTokenFilter that will be used to intercept incoming requests and verify the JWT token in the Authorization header:

public class JwtTokenFilter extends OncePerRequestFilter {  
  
    private final JwtTokenProvider jwtTokenProvider;  
  
    public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {  
        this.jwtTokenProvider = jwtTokenProvider;  
    }  
  
    @Override  
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {  
        String token = jwtTokenProvider.resolveToken(request);  
        if (token != null && jwtTokenProvider.validateToken(token)) {  
            Authentication auth = jwtTokenProvider.getAuthentication(token);  
            SecurityContextHolder.getContext().setAuthentication(auth);  
        }  
        filterChain.doFilter(request, response);  
    }  
}

The JwtTokenFilter class extends OncePerRequestFilter to ensure that it is executed only once per request. It retrieves the JWT token from the Authorization header and uses the JwtTokenProvider to validate the token. If the token is valid, it sets the authentication details in the SecurityContextHolder so that the user’s identity is available to the rest of the application.

Now, let’s create the JwtTokenProvider class that we have used in the configuration above:

public class JwtTokenProvider {  
  
    private final String secretKey;  
    private final long tokenExpiration;  
  
    public JwtTokenProvider(String secretKey, long tokenExpiration) {  
        this.secretKey = secretKey;  
        this.tokenExpiration = tokenExpiration;  
    }  
  
    public String createToken(String username) {  
        Date now = new Date();  
        Date expiryDate = new Date(now.getTime() + tokenExpiration);  
  
        return Jwts.builder()  
            .setSubject(username)  
            .setIssuedAt(now)  
            .setExpiration(expiryDate)  
            .signWith(SignatureAlgorithm.HS512, secretKey)  
            .compact();  
    }  
  
    public String resolveToken(HttpServletRequest request) {  
        String bearerToken = request.getHeader("Authorization");  
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {  
            return bearerToken.substring(7);  
        }  
        return null;  
    }  
  
    public boolean validateToken(String token) {  
        try {  
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);  
            return true;  
        } catch (SignatureException ex) {  
            // Invalid signature/claims  
        } catch (ExpiredJwtException ex) {  
            // Expired token  
        } catch (UnsupportedJwtException ex) {  
            // Unsupported JWT token  
        } catch (MalformedJwtException ex) {  
            // Malformed JWT token  
        } catch (IllegalArgumentException ex) {  
            // JWT token is empty  
        }  
        return false;  
    }  
  
    public Authentication getAuthentication(String token) {  
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();  
        List<String> roles = claims.get("roles", List.class);  
        UserPrincipal principal = new UserPrincipal(claims.getSubject(), null, AuthorityUtils.createAuthorityList(roles.toArray(new String[roles.size()])));  
        return new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities());  
    }  
}

The JwtTokenProvider class has several methods that are used to create, validate, and extract authentication details from JWT tokens. The createToken() method creates a JWT token with the given username and the expiration time that we have configured in the SecurityConfig class. The resolveToken() method extracts the JWT token from the Authorization header of the incoming request. The validateToken() method verifies the signature of the JWT token using the secret key that we have configured. It also checks if the token has expired. Finally, the getAuthentication() method extracts the username and the roles from the JWT token and creates an Authentication object with these details.

That’s it! We have now successfully implemented JWT authentication with Spring Boot. Here is a simple example of how to use the JwtTokenProvider to create and validate JWT tokens:

@Test  
public void testJwtTokenProvider() {  
    // Create a JWT token  
    String token = jwtTokenProvider.createToken("user1");  
  
    // Validate the JWT token  
    assertTrue(jwtTokenProvider.validateToken(token));  
  
    // Extract authentication details from the JWT token  
    Authentication authentication = jwtTokenProvider.getAuthentication(token);  
    assertEquals("user1", authentication.getName());  
    assertEquals(1, authentication.getAuthorities().size());  
    assertEquals("ROLE_USER", authentication.getAuthorities().iterator().next().getAuthority());  
}

In this example, we have created a JWT token with the username “user1” and a default role of “ROLE_USER”. We have then used the validateToken() and getAuthentication() methods to verify the token and extract the authentication details.

I hope this article has helped you understand how to use JWT with Spring Boot. Happy coding!