JWT,springboot整合JWT完成token的验证,token的使用,mybatis流程和原理

org.projectlombok

lombok

1.18.12

provided

com.alibaba

fastjson

1.2.73

JWT 工具类

/**

  • @author dugt1998@163.com

  • @date 2020/11/8 12:40

*/

public class JWTUtils {

//签名 自己项目中的签名

private static final String SIGN = “token!@19weawe2r24@#$@%!wewa98du”;

/**

  • 生成token

  • @param claim 传入的payload

  • @return

*/

public static S

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

tring getToken(Map<String, String> claim) {

JWTCreator.Builder builder = JWT.create();

/*

  • 1、header 用默认的就可

  • 2、设置payload .withClaim

  • 3、设置签名 .sign

*/

claim.forEach((key, value) -> {

builder.withClaim(key, value); //设置payload

});

Calendar instance = Calendar.getInstance();

instance.add(Calendar.DAY_OF_MONTH, 7);

builder.withExpiresAt(instance.getTime()); //设置token过期时间

return builder.sign(Algorithm.HMAC256(SIGN));

}

/**

  • 校验令牌

  • @param token

*/

public static DecodedJWT verifyToken(String token) {

return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);

}

}

使用拦截器拦截处理token

/**

  • @author dugt1998@163.com

  • @date 2020/11/8 13:26

*/

public class JWTInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String token = request.getHeader(“token”);

HashMap<String, Object> map = new HashMap<>();

try {

JWTUtils.verifyToken(token);

return true;

} catch (SignatureVerificationException e) {

/**

  • SignatureVerificationException :签名不一致异常

  • TokenExpiredException: 令牌过期异常

  • AlgorithmMismatchException:算法不匹配异常

  • InvalidClamException 失效的payload异常

*/

e.printStackTrace();

map.put(“msg”,“无效的签名”);

}catch (TokenExpiredException e){

e.printStackTrace();

map.put(“msg”,“该令牌已过期”);

}catch (AlgorithmMismatchException e){

e.printStackTrace();

map.put(“msg”,“算法不匹配”);

}catch (Exception e){

e.printStackTrace();

map.put(“msg”,“token无效!”);

}

map.put(“status”,false);

String errorMsg = JSONObject.toJSONString(map);

response.setContentType(“application/json; charset=UTF-8”);

PrintWriter writer = response.getWriter();

writer.print(errorMsg);

writer.close();

return false;

}

}

开启拦截器

/**

  • @author dugt1998@163.com

  • @date 2020/11/9 9:46

*/

@Configuration

public class InterceptorConfig implements WebMvcConfigurer {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(jwtInterceptor())

.addPathPatterns("/**")

.excludePathPatterns("/user/login");

}

@Bean

public JWTInterceptor jwtInterceptor(){

return new JWTInterceptor();

}

}

用户登录认证授权token信息

/**

  • 认证

  • @param user

  • @param request

  • @return

*/

@PostMapping("/login")

public Map<String, Object> login(User user, HttpServletRequest request) {

HashMap<String, Object> map = new HashMap<>();

QueryWrapper wrapper = new QueryWrapper<>();

wrapper.eq(“username”, user.getUsername());

wrapper.eq(“password”, user.getPassword());

try {

User currUser = userMapper.selectOne(wrapper);

HashMap<String, String> claim = new HashMap<>();

claim.put(“id”,currUser.getId());

claim.put(“username”,currUser.getUsername());

String token = JWTUtils.getToken(claim);

map.put(“status”,true);

map.put(“msg”,“认证成功”);

map.put(“token”,token);

return map;

} catch (Exception e) {

map.put(“status”,false);

map.put(“msg”,“认证失败”);

return map;

}

}

最后写一个接口测试一下

/**

  • 模拟请求的接口
上一篇:java高并发秒杀项目之Service层


下一篇:在 ASP.NET Core 使用 Token-based 身份验证与授权(JWT)