JavaAuthenticationPart5

JavaAuthenticationPart5

Using JWT (JSON Web Tokens) for REST APIs

JwtAuthenticationFilter.java

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
 
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;
 
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
 
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            return authenticationManager.authenticate(authenticationToken);
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException {
        String token = Jwts.builder()
                .setSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 864_000_000)) // 10 days
                .signWith(SignatureAlgorithm.HS512, "SecretKeyToGenJWTs")
                .compact();
        res.addHeader("Authorization""Bearer " + token);
    }
}

 

This class extends UsernamePasswordAuthenticationFilter and customizes it to use JWT tokens for authentication. When a login request is made, the attemptAuthentication method is triggered. It extracts the username and password from the HTTP request and creates an UsernamePasswordAuthenticationToken which is then authenticated by the AuthenticationManager. If the authentication is successful, the successfulAuthentication method is called. This method generates a JWT token using Jwts.builder(). The token contains the username as the subject and an expiration date (10 days in this case). The token is signed using the HS512 algorithm and a secret key. Finally, the token is added to the HTTP response header. This setup allows stateless authentication, where the token is sent with each request to verify the user’s identity, eliminating the need for server-side session management.

 

 

The next Part will be released in the new year on 7 January 2024.

Sumit Malhotra

Article by Sumit Malhotra

Published 31 Dec 2023