JwtUtil.java
2.43 KB
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
package com.xly.erp.common.security;
import com.xly.erp.common.exception.BizException;
import com.xly.erp.common.response.ErrorCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* JWT 签发与验证工具。HS256,密钥来自 ${JWT_SECRET}。
* docs/04 § 1.6。
*/
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
private SecretKey key;
@PostConstruct
void init() {
byte[] bytes = secret.getBytes(StandardCharsets.UTF_8);
if (bytes.length < 32) {
byte[] padded = new byte[32];
System.arraycopy(bytes, 0, padded, 0, bytes.length);
bytes = padded;
}
this.key = Keys.hmacShaKeyFor(bytes);
}
public String issue(Map<String, Object> claims, long ttlSec) {
long now = System.currentTimeMillis();
Map<String, Object> all = new HashMap<>(claims);
String sub = String.valueOf(all.remove("sub"));
String jti = UUID.randomUUID().toString();
return Jwts.builder()
.subject(sub)
.claims(all)
.id(jti)
.issuedAt(new Date(now))
.expiration(new Date(now + ttlSec * 1000L))
.signWith(key)
.compact();
}
public Map<String, Object> parse(String token) {
try {
Claims claims = Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload();
Map<String, Object> out = new HashMap<>(claims);
out.put("sub", claims.getSubject());
out.put("jti", claims.getId());
out.put("iat", claims.getIssuedAt() != null ? claims.getIssuedAt().getTime() / 1000 : null);
out.put("exp", claims.getExpiration() != null ? claims.getExpiration().getTime() / 1000 : null);
return out;
} catch (JwtException e) {
throw new BizException(ErrorCode.BAD_CREDENTIALS, "token 无效或已过期");
}
}
}