Skip to content

Commit 5d8a79c

Browse files
committed
feat: 添加 jwt token 工具类及其配置
1 parent b1fe526 commit 5d8a79c

4 files changed

Lines changed: 126 additions & 5 deletions

File tree

simple-application/src/main/resources/application.yml

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ simple:
2222
# 数据源类型
2323
type: com.zaxxer.hikari.HikariDataSource
2424
# 是否设置为默认数据源
25-
defaultFlag: true
25+
default-flag: true
2626
# 数据源配置,根据 type 而定
2727
config:
2828
jdbc-url: jdbc:mysql://localhost:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
@@ -32,7 +32,18 @@ simple:
3232
- name: db2
3333
type: com.zaxxer.hikari.HikariDataSource
3434
config:
35-
jdbcUrl: jdbc:mysql://localhost:3306/demo_cluster?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
36-
driverClassName: com.mysql.cj.jdbc.Driver
35+
jdbc-url: jdbc:mysql://localhost:3306/demo_cluster?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
36+
driver-class-name: com.mysql.cj.jdbc.Driver
3737
username: root
3838
password: xxxx
39+
jwt:
40+
# token 请求头
41+
header: token
42+
# refresh token 请求头
43+
refresh-header: refresh-token
44+
# token 过期时间
45+
expiration: 86400
46+
# refresh token 过期时间
47+
refresh-expiration: 86400
48+
# 密钥
49+
secret: 12345678123456781234567812345678
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package top.cadecode.common.util;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.junit.jupiter.api.Test;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.boot.test.context.SpringBootTest;
7+
import top.cadecode.application.Application;
8+
9+
import java.util.Collections;
10+
import java.util.Map;
11+
12+
/**
13+
* @author Cade Li
14+
* @date 2021/12/10
15+
* @description Token 工具类测试类
16+
*/
17+
@Slf4j
18+
@SpringBootTest(classes = Application.class)
19+
public class TokenUtilTest {
20+
21+
@Autowired
22+
TokenUtil tokenUtil;
23+
24+
@Test
25+
public void generateToken() {
26+
String token = tokenUtil.generateToken("user", Collections.singletonList("user"));
27+
log.info("token: {}", token);
28+
Map<String, Object> map = tokenUtil.verifyToken(token);
29+
log.info("map: {}", map);
30+
}
31+
}

simple-common/src/main/java/top/cadecode/common/enums/FrameErrorEnum.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111
@Getter
1212
public enum FrameErrorEnum implements ResponseCode {
1313

14-
JSON_TO_STR_ERROR(1000, "对象转 json 字符串失败"),
15-
JSON_TO_OBJ_ERROR(1000, "json 字符串转对象失败"),
14+
JSON_TO_STR_ERROR(1000, "对象转 json 字符串出错"),
15+
JSON_TO_OBJ_ERROR(1001, "json 字符串转对象出错"),
16+
JWT_CREATE_ERROR(1003, "创建 token 出错"),
17+
JWT_VERIFY_ERROR(1003, "解析 token 出错"),
1618
;
1719

1820
private final String code;
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package top.cadecode.common.util;
2+
3+
import com.nimbusds.jose.*;
4+
import com.nimbusds.jose.crypto.MACSigner;
5+
import com.nimbusds.jose.crypto.MACVerifier;
6+
import com.nimbusds.jwt.JWTClaimsSet;
7+
import com.nimbusds.jwt.SignedJWT;
8+
import lombok.Data;
9+
import lombok.SneakyThrows;
10+
import org.springframework.boot.context.properties.ConfigurationProperties;
11+
import org.springframework.stereotype.Component;
12+
import top.cadecode.common.core.exception.CommonException;
13+
import top.cadecode.common.enums.FrameErrorEnum;
14+
15+
import java.util.Date;
16+
import java.util.List;
17+
import java.util.Map;
18+
19+
/**
20+
* @author Cade Li
21+
* @date 2021/12/10
22+
* @description Token 工具类
23+
*/
24+
@Data
25+
@Component
26+
@ConfigurationProperties(prefix = "simple.jwt")
27+
public class TokenUtil {
28+
29+
private String header;
30+
private String refreshHeader;
31+
private Long expiration;
32+
private Long refreshExpiration;
33+
private String secret;
34+
35+
/**
36+
* 生成 token
37+
*
38+
* @param name 用户名
39+
* @param roles 角色
40+
* @return token 字符串
41+
*/
42+
public String generateToken(String name, List<String> roles) {
43+
long expiredTime = new Date().getTime() + expiration * 1000;
44+
JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);
45+
JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder()
46+
.claim("name", name).
47+
claim("roles", roles)
48+
.expirationTime(new Date(expiredTime)).build();
49+
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet);
50+
try {
51+
signedJWT.sign(new MACSigner(secret));
52+
return signedJWT.serialize();
53+
} catch (JOSEException e) {
54+
throw CommonException.of(FrameErrorEnum.JWT_CREATE_ERROR).suppressed(e);
55+
}
56+
}
57+
58+
/**
59+
* 校验 token
60+
*
61+
* @param token token 字符串
62+
* @return 是否通过校验
63+
*/
64+
public Map<String, Object> verifyToken(String token) {
65+
try {
66+
JWSObject jwsObject = JWSObject.parse(token);
67+
JWSVerifier verifier = new MACVerifier(secret);
68+
boolean verify = jwsObject.verify(verifier);
69+
if (verify) {
70+
return jwsObject.getPayload().toJSONObject();
71+
}
72+
return null;
73+
} catch (Exception e) {
74+
throw CommonException.of(FrameErrorEnum.JWT_VERIFY_ERROR).suppressed(e);
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)