JWTS token for Spring REST API

01-07-2022

We can integrate JWTS token for Spring REST API by using following component:


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultClaims;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.function.Function;
@Component
public class JwtUtils {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
    private final String jwtSecret = "4528482B4D6251655468576D5A7134743777217A25432646294A404E63526655";
    private final int jwtExpirationMs = 30_60_1000;

    public String generateJwtToken(String username, String reportingUnit) {

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setHeaderParam("ReportingUnit", reportingUnit)
                .setExpiration(expirationDate())
                .signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)))
                .compact();
    }
    private Date expirationDate(){
        return new Date((new Date()).getTime() + jwtExpirationMs);
    }
    public String getUserNameFromJwtToken(String token) {
        DefaultClaims result = (DefaultClaims) jwtBuilder().parse(token).getBody();
        return result.getSubject();
    }
    public String getReportingHeader(String token) {
        token = token.replace("Bearer ","");
        return (String) jwtBuilder()
                .parse(token).getHeader().get("ReportingUnit");

    }

    public boolean validateJwtToken(String token) {
        try {
            return isSigned(token)&& !isTokenExpired(token) ;
        } catch (Exception e) {
            return false;
        }
    }
    private JwtParser jwtBuilder() {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret))).build();
    }
    public boolean isSigned(String token) {
        return jwtBuilder().isSigned(token);
    }
    public boolean isTokenExpired(String token) {
        return expirationDate().getTime() - extractExpiration(token).getTime() > jwtExpirationMs;
    }

    private Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    private <T> T extractClaim(String token , Function<Claims, T> claimResolver) {
        final Claims claim= extractAllClaims(token);
        return claimResolver.apply(claim);
    }

    private Claims extractAllClaims(String token) {
        return jwtBuilder().parseClaimsJws(token).getBody();
    }
}

© 2019 All rights reserved. Codesenior.COM