JWT的 Token 要经过加密才能返回给客户端,包括客户端上传的 Token ,后端项目需要验证核 实。于是我们需要一个JWT工具类,用来 加密Token 和 验证Token 的有效性。
一、导入依赖库1.二、定义密钥和过期时间2. 6.org.apache.shiro 3. shiro-web 4.1.5.3 5.7. 11.org.apache.shiro 8. shiro-spring 9.1.5.3 10.12. 16.com.auth0 13. java-jwt 14.3.10.3 15.17. 21.org.springframework.boot 18. spring-boot-configuration-processor 19.true 20.22. 26.org.apache.commons 23. commons-lang3 24.3.11 25.27. 31.org.apache.httpcomponents 28. httpcore 29.4.4.13 30.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. }



