当前位置:   article > 正文

SpringBoot 整合 JWT 实现 Token 验证_springboot jwt refreshtoken

springboot jwt refreshtoken

前言

        在Spring Security整合oauth2实现认证token也不满足实际生产需求的时候,可以整合Jwt实现token认证,完全手写获取token,认证token的方法。


Maven依赖包

  1. <dependency>
  2. <groupId>com.auth0</groupId>
  3. <artifactId>java-jwt</artifactId>
  4. <version>3.11.0</version>
  5. </dependency>

业务实现

1、创建Jwt生成验证token工具类

  1. import com.auth0.jwt.JWT;
  2. import com.auth0.jwt.JWTVerifier;
  3. import com.auth0.jwt.algorithms.Algorithm;
  4. import com.auth0.jwt.exceptions.JWTVerificationException;
  5. import com.auth0.jwt.interfaces.DecodedJWT;
  6. import com.bw.dsm.entity.base.TokenEntity;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.util.*;
  10. public class AppJwtUtil {
  11. private static final Logger LOGGER = LoggerFactory.getLogger(AppJwtUtil.class);
  12. public static final String secretKey = "asdfghjklsed";
  13. public static final long tokenExpireTime = 7200000;//#token过期时间:单位毫秒 2个小时
  14. public static final long refreshTokenExpireTime = 72000000000L;//refreshToken过期时间:单位毫秒
  15. public static final String jwtRefreshTokenKeyFormat = "jwt_refresh_token:";//refreshToken 存储key
  16. public static final String jwtBlacklistKeyFormat = "jwt_black_key:";//#token黑名单 存储key
  17. /**
  18. * 生成jwt
  19. *
  20. * @param platformID
  21. * @return
  22. */
  23. public static String buildJWT(String platformID,String platformSecret) {
  24. Date now = new Date();
  25. Algorithm algo = Algorithm.HMAC256(secretKey);
  26. String token = JWT.create()
  27. .withIssuer("MING")
  28. .withIssuedAt(now)
  29. .withExpiresAt(new Date(now.getTime() + tokenExpireTime))
  30. .withClaim("platformID", platformID)// 保存身份标识
  31. .withClaim("platformSecret",platformSecret)
  32. .sign(algo);
  33. return token;
  34. }
  35. /**
  36. * JWT验证
  37. *
  38. * @param token
  39. * @return userName
  40. */
  41. public static TokenEntity verifyJWT(String token) {
  42. TokenEntity tokenEntity = new TokenEntity();
  43. try {
  44. Algorithm algorithm = Algorithm.HMAC256(secretKey);
  45. JWTVerifier verifier = JWT.require(algorithm)
  46. .withIssuer("MING")
  47. .build();
  48. DecodedJWT jwt = verifier.verify(token);
  49. tokenEntity.setPlatformID(jwt.getClaim("platformID").asString());
  50. tokenEntity.setPlatformSecret(jwt.getClaim("platformSecret").asString());
  51. return tokenEntity;
  52. } catch (JWTVerificationException e) {
  53. LOGGER.error(e.getMessage(), e);
  54. return tokenEntity;
  55. }
  56. }
  57. }

2、创建/oauth/token接口获取token

  1. @RestController
  2. @RequestMapping("/interaction/v1")
  3. public class IndexController {
  4. @Value("${base.param.platformID}")
  5. private String platformID;
  6. @Value("${base.param.platformSecret}")
  7. private String platformSecret;
  8. @RequestMapping(value = "/oauth/token",method = RequestMethod.POST)
  9. public String getToken(@RequestBody String getParamInfo){
  10. MsgResult msg = new MsgResult();
  11. TokenData tokenData = new TokenData();
  12. getParamInfo = getParamInfo.replace("[+]","+");
  13. try {
  14. // 校验生成服务消息主题
  15. String data = Common.validMessage( getParamInfo );
  16. TokenEntity tokenEntity = Common.makeEntity(data,TokenEntity.class);
  17. if (!platformID.equals(tokenEntity.getPlatformID())){
  18. tokenData.setFailReason(1);
  19. throw new BusinessException("4004","平台标识错误");
  20. }
  21. if (!platformSecret.equals(tokenEntity.getPlatformSecret())){
  22. tokenData.setFailReason(2);
  23. throw new BusinessException("4004","平台秘钥错误");
  24. }
  25. String token = AppJwtUtil.buildJWT(
  26. tokenEntity.getPlatformID(),tokenEntity.getPlatformSecret());
  27. tokenData.setSuccstat(0);
  28. tokenData.setFailReason(0);
  29. tokenData.setAccessToken( token );
  30. tokenData.setExpiresIn(7200000);
  31. msg.setCode("0");
  32. msg.setMesg("请求成功");
  33. } catch (BusinessException b){
  34. msg.setCode(b.getCode());
  35. msg.setMesg(b.getMessage());
  36. tokenData.setSuccstat(1);
  37. } catch (Exception e){
  38. msg.setCode("500");
  39. msg.setMesg(e.getMessage());
  40. tokenData.setSuccstat(1);
  41. tokenData.setFailReason(3);
  42. }
  43. msg.setData(Common.AESJaiMi(Common.makeJson(tokenData)));
  44. return Common.msgResult(msg);
  45. }
  46. }

 这里是我的生产环境上的获取token接口,主要功能就是根据传递过来的参数使用Jwt工具类创建token,再组合成规定的返回格式返回给对方。

3、创建接口拦截验证token类

  1. @Component
  2. public class JwtInterceptors implements HandlerInterceptor {
  3. @Value("${base.param.platformID}")
  4. private String platformID;
  5. @Value("${base.param.platformSecret}")
  6. private String platformSecret;
  7. @Override
  8. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  9. MsgResult msg = new MsgResult();
  10. //获取请求头部令牌
  11. String auth = request.getHeader("Authorization");
  12. try {
  13. if (StringUtils.isNotBlank(auth) && auth.indexOf("Bearer") >= 0) {
  14. auth = auth.substring("Bearer ".length() - 1, auth.length()).trim();
  15. } else {
  16. throw new BusinessException("4002","Token错误");
  17. }
  18. TokenEntity tokenEntity = AppJwtUtil.verifyJWT(auth);
  19. if (!platformID.equals(tokenEntity.getPlatformID())){
  20. throw new BusinessException("4002","Token错误");
  21. }
  22. if (!platformSecret.equals(tokenEntity.getPlatformSecret())){
  23. throw new BusinessException("4002","Token错误");
  24. }
  25. // //验证令牌
  26. // DecodedJWT decodedJWT = JwtUtils.verify(token);
  27. return true;
  28. } catch (BusinessException b){
  29. msg.setCode(b.getCode());
  30. msg.setMesg(b.getMessage());
  31. msg.setData(Common.AESJaiMi(auth));
  32. } catch (Exception e){
  33. msg.setCode("500");
  34. msg.setMesg(e.getMessage());
  35. msg.setData(Common.AESJaiMi(auth));
  36. }
  37. // 转json
  38. String json = Common.msgResult(msg);
  39. response.setContentType("application/json;charset=utf-8");
  40. response.getWriter().println(json);
  41. return false;
  42. }
  43. }

基于HandlerInterceptor的实现类,对接口进行拦截,然后获取接口传递过来的token,用Jwt工具类进行解密,如果token验证通过则返回true并放行接口,验证不通过则返回错误信息。

4、创建拦截路径类

  1. @Configuration
  2. public class WebConfigurer implements WebMvcConfigurer {
  3. @Autowired
  4. private JwtInterceptors jwtInterceptors;
  5. @Override
  6. public void addInterceptors(InterceptorRegistry registry) {
  7. registry.addInterceptor(jwtInterceptors)
  8. // 放行接口
  9. .excludePathPatterns("/interaction/v1/oauth/token")
  10. .addPathPatterns("/**");
  11. }
  12. }

5、测试获取token接口

至此功能实现。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/368079?site
推荐阅读
相关标签
  

闽ICP备14008679号