DEV Community

Rajesh Mishra
Rajesh Mishra

Posted on Originally published at howtostartprogramming.in

Spring Security JWT authentication and authorization tutorial — Complete Guide

Spring Security JWT authentication and authorization tutorial — Complete Guide

A practical, in-depth guide to Spring Security JWT authentication and authorization tutorial with examples.

INTRO

Modern APIs are expected to be stateless, scalable, and secure out of the box. Yet, every time you spin up a new Spring Boot service, you end up wrestling with session cookies, CSRF tokens, and a maze of configuration classes just to protect a single endpoint. The result is brittle code that either over‑exposes resources or locks down everything, forcing developers to write ad‑hoc filters that are hard to test and maintain.

JSON Web Tokens (JWT) provide a clean solution: a self‑contained, signed token that travels with each request, allowing the server to stay stateless while still enforcing fine‑grained access control. The challenge isn’t the concept—it’s wiring JWT correctly into Spring Security’s filter chain, handling token refresh, and mapping claims to authorities without turning your configuration into a spaghetti mess. This guide cuts through the noise, delivering a production‑ready setup you can drop into any Spring Boot project.

WHAT YOU'LL LEARN

  • How to generate and sign JWTs with asymmetric keys, keeping private keys out of source control.
  • Configuring Spring Security’s filter chain to validate tokens, reject tampered requests, and populate Authentication objects automatically.
  • Mapping JWT claims to Spring GrantedAuthority objects for role‑based access control.
  • Implementing a refresh‑token endpoint that rotates tokens safely and mitigates replay attacks.
  • Testing the security layer with MockMvc and integration tests to guarantee your endpoints behave as expected.
  • Common pitfalls (e.g., token expiration handling, clock skew, and insecure token storage) and how to avoid them.

A SHORT CODE SNIPPET

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtProvider jwtProvider;
private final UserDetailsService userDetailsService;

public JwtAuthenticationFilter(JwtProvider jwtProvider,
UserDetailsService userDetailsService) {
this.jwtProvider = jwtProvider;
this.userDetailsService = userDetailsService;
}

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String token = jwtProvider.resolveToken(request);
if (token != null && jwtProvider.validateToken(token)) {
String username = jwtProvider.getUsername(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
}
Enter fullscreen mode Exit fullscreen mode

The snippet shows the heart of a JWT‑based security filter: extracting the token, validating its signature and expiration, then building a Spring Authentication object that downstream code can rely on.

KEY TAKEAWAYS

  • Stateless security is achievable with Spring Security – By delegating authentication to a JWT filter, you eliminate server‑side sessions and simplify horizontal scaling.
  • Never hard‑code secrets – Use environment variables or a secret manager for signing keys; the guide demonstrates loading RSA keys from a keystore.
  • Claims drive authorization – Store roles or permissions inside the token and translate them to GrantedAuthority objects, keeping your business logic clean.
  • Refresh tokens are a must – Short‑lived access tokens reduce attack windows, while refresh tokens let clients stay logged in without re‑authenticating.

👉 Read the complete guide with step-by-step examples, common mistakes, and production tips:
Spring Security JWT authentication and authorization tutorial — Complete Guide

Top comments (0)