How To Create A JWT Authentication In Spring Boot

JWT authentication module in Spring Boot using the jjwt library:

Step 1: Add dependencies Add the following dependency to your Maven pom.xml file:

				
					<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
				
			

Step 2: Create the JWT authentication module Create a new class called JwtAuthModule with the following contents:

				
					import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtAuthModule {

    @Value("${jwt.secretKey}")
    private String secretKey;

    @Value("${jwt.expirationTime}")
    private long expirationTime;

    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expirationTime);

        JwtBuilder builder = Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS256, secretKey);

        return builder.compact();
    }

    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
}
				
			

Step 3: Configure properties In your application.properties file, add the following properties:

				
					jwt.secretKey=your-secret-key
jwt.expirationTime=3600000  # Token expiration time in milliseconds
				
			

Step 4: Using the JWT authentication module You can use the JwtAuthModule class to generate and validate JWT tokens. Here’s an example of how you can use it:

				
					import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private JwtAuthModule jwtAuthModule;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        // Authenticate user and retrieve username
        String username = authenticateUser(request.getUsername(), request.getPassword());

        // Generate JWT token
        String token = jwtAuthModule.generateToken(username);

        // Return the token in the response
        return ResponseEntity.ok(new LoginResponse(token));
    }

    @GetMapping("/user")
    public ResponseEntity<?> getUser(@RequestHeader("Authorization") String token) {
        // Extract username from token
        String username = jwtAuthModule.getUsernameFromToken(token);

        // Fetch user details using the username

        // Return the user in the response
        return ResponseEntity.ok(new UserResponse(username));
    }

    private String authenticateUser(String username, String password) {
        // Perform authentication logic
        // ...

        // Return the username upon successful authentication
        return username;
    }
}
				
			

In this example, the generateToken method generates a JWT token based on a username. The getUsernameFromToken method extracts the username from a token. The validateToken method checks if a token is valid.

Please note that this is a basic example, and you may need to customize it further based on your specific requirements, such as integrating it with your authentication workflow and handling token storage.