|
24 | 24 | import io.jsonwebtoken.Jwts; |
25 | 25 | import io.jsonwebtoken.SignatureAlgorithm; |
26 | 26 | import lombok.extern.slf4j.Slf4j; |
| 27 | +import org.springframework.boot.context.properties.ConfigurationProperties; |
| 28 | +import org.springframework.context.annotation.Configuration; |
| 29 | +import org.springframework.util.StringUtils; |
27 | 30 |
|
| 31 | +import java.util.ArrayList; |
28 | 32 | import java.util.Date; |
| 33 | +import java.util.List; |
29 | 34 |
|
30 | 35 | /** date:2022/12/6 author:yzf project_name:backend */ |
31 | 36 | @Slf4j |
| 37 | +@Configuration |
| 38 | +@ConfigurationProperties(prefix = "jwt.sign") |
32 | 39 | public class JJwtTool { |
33 | | - private static String secret = |
34 | | - "HSyJ0eXAiOiJKV1QasdfffffffSd3g8923402347523fffasdfasgwaegwaegawegawegawegawetwgewagagew" |
35 | | - + "asdf23r23DEEasdfawef134t2fawt2g325gafasdfasdfiLCJhbGciOiJIUzI1NiJ9"; |
| 40 | + |
| 41 | + private static List<String> jwtCache = new ArrayList<>(); |
| 42 | + private static String secret; |
| 43 | + |
| 44 | + public String getSecret() { |
| 45 | + return secret; |
| 46 | + } |
| 47 | + |
| 48 | + public void setSecret(String payload) { |
| 49 | + secret = payload; |
| 50 | + } |
36 | 51 |
|
37 | 52 | public static String generateToken(User user) { |
38 | 53 | log.info("user=" + user.toString()); |
39 | 54 | Date now = new Date(); |
40 | 55 | // Calendar instance = Calendar.getInstance(); |
41 | 56 | // instance.add(Calendar.HOUR_OF_DAY, 24); |
42 | 57 | Date expireDate = new Date(new Date().getTime() + (1000 * 60 * 60 * 10)); |
43 | | - return Jwts.builder() |
44 | | - .setHeaderParam("type", "JWT") |
45 | | - .setSubject(user.getId() + "") |
46 | | - .setIssuedAt(now) // 签发时间 |
47 | | - .claim("userId", user.getId()) |
48 | | - .claim("name", user.getName()) |
49 | | - .setExpiration(expireDate) // 过期时间 |
50 | | - .signWith(SignatureAlgorithm.HS512, secret) |
51 | | - .compact(); |
| 58 | + String compact = |
| 59 | + Jwts.builder() |
| 60 | + .setHeaderParam("type", "JWT") |
| 61 | + .setSubject(user.getId() + "") |
| 62 | + .setIssuedAt(now) // 签发时间 |
| 63 | + .claim("userId", user.getId()) |
| 64 | + .claim("name", user.getName()) |
| 65 | + .setExpiration(expireDate) // 过期时间 |
| 66 | + .signWith(SignatureAlgorithm.HS512, secret) |
| 67 | + .compact(); |
| 68 | + if (StringUtils.hasLength(compact) && !jwtCache.contains(compact)) { |
| 69 | + jwtCache.add(compact); |
| 70 | + } |
| 71 | + return compact; |
52 | 72 | } |
53 | 73 |
|
54 | 74 | /** 解析token */ |
55 | 75 | public static Claims getClaimsByToken(String token) { |
56 | 76 | try { |
| 77 | + if (StringUtils.hasLength(token) && !jwtCache.contains(token)) { |
| 78 | + return null; |
| 79 | + } |
57 | 80 | return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); |
58 | 81 | } catch (Exception e) { |
59 | 82 | System.out.println("validate is token error"); |
|
0 commit comments