public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "id";
private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
public static String generateTokenExpireInMinutes(Integer userId, int expire) {
Map<String, Object> claimMaps = new HashMap<>();
claimMaps.put(JWT_PAYLOAD_USER_KEY,userId);
return Jwts.builder()
.addClaims(claimMaps)
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.compressWith(CompressionCodecs.GZIP)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setSubject("system")
.setIssuer("heima")
.setAudience("app")
.signWith(SignatureAlgorithm.HS256, generalKey())
.compact();
}
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static String generateTokenExpireInSeconds(Integer userId, int expire) {
Map<String, Object> claimMaps = new HashMap<>();
claimMaps.put(JWT_PAYLOAD_USER_KEY,userId);
return Jwts.builder()
.addClaims(claimMaps)
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.compressWith(CompressionCodecs.GZIP)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setSubject("system")
.setIssuer("heima")
.setAudience("app")
.signWith(SignatureAlgorithm.HS256, generalKey())
.compact();
}
private static Jws<Claims> parserToken(String token) {
return Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(token);
}
private static String createJTI() {
return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
public static Payload getInfoFromToken(String token) {
Jws<Claims> claimsJws = parserToken(token);
Claims body = claimsJws.getBody();
Payload claims = new Payload();
claims.setId(body.getId());
claims.setUserId(Integer.valueOf(body.get(JWT_PAYLOAD_USER_KEY).toString()));
claims.setExpiration(body.getExpiration());
return claims;
}
}