@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.
In the new version of the dependencies they basically dropped
set
. So instead ofyou use:
A github link from one of my demo projects as a further resource.
Youtube tutorial where i explain this class (from 26:24 mark)