What should I put instead of old Jwt methods?

42 views Asked by At
@Component
public class JwtTokenProvider {

    @Value("${petapp.app.secret}")
    private String APP_SECRET;
    @Value("${petapp.expires.in}")
    private Long EXPIRES_IN;

    public String generateJwtToken(Authentication auth){
        JwtUserDetails userDetails = (JwtUserDetails) auth.getPrincipal();
        Date expireDate = new Date(new Date().getTime() + EXPIRES_IN);
        return Jwts.builder().setSubject(Long.toString(userDetails.getId()))
                .setIssuedAt(new Date()).setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, APP_SECRET).compact();
    }

    Long getUserIdFromJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(APP_SECRET).build().parseSignedClaims(token).getBody();
        return Long.parseLong(claims.getSubject());
    }

    boolean validateToken(String token){
        try{
            Jwts.parser().setSigningKey(APP_SECRET).build().parseSignedClaims(token);
            return !isTokenExpired(token);
        }catch(SignatureException | MalformedJwtException | ExpiredJwtException | UnsupportedJwtException |
               IllegalArgumentException e){
            return false;
        }
    }

    private boolean isTokenExpired(String token) {
        Date expiration = Jwts.parser().setSigningKey(APP_SECRET).build().parseSignedClaims(token).getBody().getExpiration();
        return expiration.before(new Date());
    }

}

I'm trying to make a authentication system for login and register to my app. I was using old resources to make this code part. I can succesfully register but I can't login to system.Yellow parts for deprecated methods.

1

There are 1 answers

0
J Asgarov On

In the new version of the dependencies they basically dropped set. So instead of

Jwts.builder().setSubject(Long.toString(userDetails.getId()))
                .setIssuedAt(new Date()).setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, APP_SECRET).compact();

you use:

Jwts.builder().subject(Long.toString(userDetails.getId()))
    .issuedAt(new Date()).expiration(expireDate)               
    .signWith(Keys.hmacShaKeyFor(APP_SECRET.getBytes())).compact();

A github link from one of my demo projects as a further resource.

Youtube tutorial where i explain this class (from 26:24 mark)