JwtUtil.java
2.73 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
76
77
78
79
80
81
82
83
84
85
86
87
package com.diligrp.rider.config;
import com.diligrp.rider.common.exception.BizException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expire}")
private long expire;
private Key getKey() {
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
public String generateToken(Long riderId) {
Map<String, Object> claims = new HashMap<>();
claims.put("riderId", riderId);
return buildToken(claims);
}
/** 生成骑手 token,携带 riderId + cityId */
public String generateRiderToken(Long riderId, Long cityId) {
Map<String, Object> claims = new HashMap<>();
claims.put("riderId", riderId);
claims.put("cityId", cityId);
return buildToken(claims);
}
/** 生成管理员 token,携带 role 和 id */
public String generateAdminToken(Long adminId, String role) {
Map<String, Object> claims = new HashMap<>();
claims.put("adminId", adminId);
claims.put("role", role);
return buildToken(claims);
}
private String buildToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expire * 1000))
.signWith(getKey(), SignatureAlgorithm.HS256)
.compact();
}
public Long getRiderIdFromToken(String token) {
try {
Claims claims = parseClaims(token);
return ((Number) claims.get("riderId")).longValue();
} catch (ExpiredJwtException e) {
throw new BizException(700, "登录状态已过期,请重新登录");
} catch (Exception e) {
throw new BizException(700, "登录状态失效,请重新登录");
}
}
public Claims getAdminClaims(String token) {
try {
return parseClaims(token);
} catch (ExpiredJwtException e) {
throw new BizException(700, "登录状态已过期,请重新登录");
} catch (Exception e) {
throw new BizException(700, "登录状态失效,请重新登录");
}
}
private Claims parseClaims(String token) {
return Jwts.parserBuilder()
.setSigningKey(getKey())
.build()
.parseClaimsJws(token)
.getBody();
}
}