JwtUtil.java
2.53 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.example.erp.common.util;
import com.example.erp.common.constants.AuthErrorCode;
import com.example.erp.common.exception.BizException;
import com.example.erp.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
@Component
@RequiredArgsConstructor
public class JwtUtil {
private final JwtProperties properties;
private SecretKey key() {
return Keys.hmacShaKeyFor(properties.getSecret().getBytes(StandardCharsets.UTF_8));
}
public String generateAccessToken(String userId, String username, String userType, String brandId) {
long now = System.currentTimeMillis();
return Jwts.builder()
.subject(userId)
.claim("username", username)
.claim("userType", userType)
.claim("brandId", brandId)
.issuedAt(new Date(now))
.expiration(new Date(now + properties.getAccessTokenExpiry() * 1000))
.signWith(key(), Jwts.SIG.HS256)
.compact();
}
public String generateRefreshToken(String userId, String brandId) {
long now = System.currentTimeMillis();
return Jwts.builder()
.subject(userId)
.claim("brandId", brandId)
.claim("type", "refresh")
.issuedAt(new Date(now))
.expiration(new Date(now + properties.getRefreshTokenExpiry() * 1000))
.signWith(key(), Jwts.SIG.HS256)
.compact();
}
public Claims parseAccessToken(String token) {
return doParse(token);
}
public Claims parseRefreshToken(String token) {
Claims claims = doParse(token);
if (!"refresh".equals(claims.get("type", String.class))) {
throw new BizException(AuthErrorCode.REFRESH_TOKEN_INVALID, "Refresh Token 已失效,请重新登录");
}
return claims;
}
private Claims doParse(String token) {
try {
return Jwts.parser()
.verifyWith(key())
.build()
.parseSignedClaims(token)
.getPayload();
} catch (JwtException e) {
throw new BizException(AuthErrorCode.REFRESH_TOKEN_INVALID, "Token 已失效,请重新登录");
}
}
}