栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

创建JWT工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建JWT工具类

JWT的 Token 要经过加密才能返回给客户端,包括客户端上传的 Token ,后端项目需要验证核 实。于是我们需要一个JWT工具类,用来 加密Token 和 验证Token 的有效性。

一、导入依赖库
1. 
2. org.apache.shiro
3. shiro-web
4. 1.5.3
5. 
6. 
7. org.apache.shiro
8. shiro-spring
9. 1.5.3
10. 
11. 
12. com.auth0
13. java-jwt
14. 3.10.3
15. 
16. 
17. org.springframework.boot
18. spring-boot-configuration-processor
19. true
20. 
21. 
22. org.apache.commons
23. commons-lang3
24. 3.11
25. 
26. 
27. org.apache.httpcomponents
28. httpcore
29. 4.4.13
30. 
31. 
32. org.springframework.boot
33. spring-boot-starter-aop
34. 
二、定义密钥和过期时间

我建议大家把密钥和过期时间定义到SpringBoot配置文件中,然后再值注入到JavaBean中,这样 维护起来比较方便。

三、创建JWT工具类

创建 JwtUtil 类

1. package com.example.emos.wx.config.shiro;
2. import cn.hutool.core.date.DateField;
3. import cn.hutool.core.date.DateUtil;
4. import com.auth0.jwt.JWT;
5. import com.auth0.jwt.JWTCreator;
6. import com.auth0.jwt.JWTVerifier;
7. import com.auth0.jwt.algorithms.Algorithm;
8. import com.auth0.jwt.interfaces.DecodedJWT;
9. import com.example.emos.wx.exception.EmosException;
10. import lombok.extern.slf4j.Slf4j;
11. import org.springframework.beans.factory.annotation.Value;
12. import org.springframework.stereotype.Component;
13. import java.util.Date;
14. @Component
15. @Slf4j
16. public class JwtUtil {
17. //密钥
18. @Value("${emos.jwt.secret}")
19. private String secret;
20. //过期时间(天)
21. @Value("${emos.jwt.expire}")
22. private int expire;
23. public String createToken(int userId) {
24. Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,
expire).toJdkDate();
25. Algorithm algorithm = Algorithm.HMAC256(secret); //创建加密算法对象
26. JWTCreator.Builder builder = JWT.create();
27. String token = builder.withClaim("userId",
userId).withExpiresAt(date).sign(algorithm);
28. return token;
29. }
30. public int getUserId(String token) {
31. try {
32. DecodedJWT jwt = JWT.decode(token);
33. return jwt.getClaim("userId").asInt();
34. } catch (Exception e) {
35. throw new EmosException("令牌无效");
36. }
37. }
38. public void verifierToken(String token) {
39. Algorithm algorithm = Algorithm.HMAC256(secret); //创建加密算法对象
40. JWTVerifier verifier = JWT.require(algorithm).build();
41. verifier.verify(token);
42. }
43. }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/826524.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号