ASP.NET  

How to Implement JWT Authentication in Java Spring Boot REST API

🌟 Introduction

In modern web applications, security is a top priority. One popular way to secure REST APIs is by using JWT (JSON Web Token) authentication. JWT allows your API to verify users’ identities and protect sensitive endpoints without storing session data on the server.

πŸ”‘ 1. What is JWT?

JWT (JSON Web Token) is a compact token format that contains user information (claims) and is signed digitally.

  • Structure: JWT has three parts separated by dots:

    1. Header

    2. Payload

    3. Signature

  • Example

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
  • Purpose: JWT allows stateless authentication where the server does not need to store user sessions.

πŸ—οΈ 2. Create a Spring Boot Project

  • Use Spring Initializr to create a new project.

  • Add dependencies:

    • Spring Web

    • Spring Security

    • Spring Data JPA (optional, for storing user data)

    • jjwt (for JWT token creation)

πŸ‘€ 3. Define User Model and Repository

  • Create a User entity representing users in your database.

  • Create a UserRepository to handle database operations.

Example

@Entity
public class User {
    @Id @GeneratedValue
    private Long id;
    private String username;
    private String password;
    private String role;
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}

πŸ”‘ 4. Configure Spring Security

  • Create a SecurityConfig class that extends WebSecurityConfigurerAdapter.

  • Disable the default login form and enable the JWT filter.

Example

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

πŸ› οΈ 5. Create JWT Utility Class

  • Generate and validate JWT tokens.

  • Use io.jsonwebtoken (jjwt) library.

Example

@Component
public class JwtUtil {
    private String secret = "mySecretKey";

    public String generateToken(String username) {
        return Jwts.builder()
                   .setSubject(username)
                   .setIssuedAt(new Date())
                   .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                   .signWith(SignatureAlgorithm.HS256, secret)
                   .compact();
    }

    public String extractUsername(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
    }

    public boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
}

πŸ”’ 6. Implement Authentication Controller

  • Create endpoints for login and token generation.

Example

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired private AuthenticationManager authenticationManager;
    @Autowired private JwtUtil jwtUtil;
    @Autowired private UserDetailsService userDetailsService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody AuthRequest request) {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
        final String token = jwtUtil.generateToken(userDetails.getUsername());
        return ResponseEntity.ok(new AuthResponse(token));
    }
}
  • AuthRequest and AuthResponse are simple POJOs to carry request and response data.

🧩 7. Create JWT Filter

  • Intercepts incoming requests, extracts the JWT token from headers, and validates it.

Example

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired private JwtUtil jwtUtil;
    @Autowired private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        String username = null;
        String token = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            username = jwtUtil.extractUsername(token);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtUtil.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        chain.doFilter(request, response);
    }
}

βœ… 8. Test Your REST API

  • Start the Spring Boot application.

  • Use Postman or curl to test:

    1. /auth/login with username/password β†’ get JWT token.

    2. Access protected endpoints with Authorization: Bearer <token> header.

Example curl command

curl -H "Authorization: Bearer <your_token_here>" http://localhost:8080/api/protected
  • If everything is correct, the request succeeds; otherwise, it returns 401 Unauthorized.

πŸ“ Summary

JWT authentication in Spring Boot allows you to build secure, stateless REST APIs. By following these steps β€” creating a user model, configuring Spring Security, generating JWT tokens, implementing filters, and testing your endpoints β€” you can secure your API effectively. JWT is widely used in modern web and mobile applications because it is lightweight, secure, and scalable.