1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
| @Component public class JwtUtils {
private static JwtProperties jwtProperties;
@Autowired public void setJwtProperties(JwtProperties jwtProperties) { JwtUtils.jwtProperties = jwtProperties; }
private static ObjectMapper objectMapper;
@Autowired public static void setObjectMapper(ObjectMapper objectMapper) { JwtUtils.objectMapper = objectMapper; }
private static SecretKey generateKey() throws Exception { String secret = jwtProperties.getSecret(); byte[] encodedKey = Base64.decodeBase64(secret); SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); return key; }
public static String createJWT(String id, String subject, String issuer, Long ttlMillis, Map<String, Object> claims) throws Exception { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; SecretKey key = generateKey();
JwtBuilder builder = Jwts.builder(); builder.signWith(signatureAlgorithm, key); builder.setId(id); builder.setIssuedAt(new Date()); builder.setIssuer(issuer); builder.setSubject(subject); if (ObjectUtils.allNotNull(claims)) { builder.setClaims(claims); }
if (ttlMillis >= 0) { Long expiredMillis = System.currentTimeMillis() + ttlMillis; Date expiredDate = new Date(expiredMillis); builder.setExpiration(expiredDate); } return builder.compact(); }
public static String createJWT(String id, String subject, Long ttlMillis, Map<String, Object> claims) throws Exception { return createJWT(id, subject, jwtProperties.getIssuer(), ttlMillis, claims); }
public static String createJWT(String id, String subject, Map<String, Object> claims) throws Exception { return createJWT(id, subject, jwtProperties.getIssuer(), jwtProperties.getTtl(), claims); }
public static String createJWT(String id, String subject) throws Exception { return createJWT(id, subject, jwtProperties.getIssuer(), jwtProperties.getTtl(), null); }
public static Claims parseJWT(String jwt) throws Exception { SecretKey key = generateKey(); Claims claims = Jwts.parser() .setSigningKey(key) .parseClaimsJws(jwt).getBody(); return claims; }
public static boolean isExpiration(String jwt) throws Exception { Claims claims = JwtUtils.parseJWT(jwt); return claims.getExpiration().before(new Date()); } }
|