JWT整合SpringBoot(拦截器)

1、为什么使用拦截器拦截Token

上个例子我们看到了,每请求一个接口都要验证Token,这样的话就有大量代码冗余

单体应用:用拦截器

分布式应用:在网关中拦截

2、上代码

首先得编写一个拦截器:

  1. package com.zym.springboot_jwt.interceptor;
  2. import com.auth0.jwt.exceptions.AlgorithmMismatchException;
  3. import com.auth0.jwt.exceptions.SignatureVerificationException;
  4. import com.auth0.jwt.exceptions.TokenExpiredException;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import com.zym.springboot_jwt.util.JWTUtils;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.web.servlet.HandlerInterceptor;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. @Slf4j
  14. public class JWTInterceptor implements HandlerInterceptor {
  15. @Override
  16. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  17. //获取请求头中的Token
  18. String token = request.getHeader("token");
  19. Map<String,Object> map = new HashMap<>();
  20. log.info("当前Token为[{}]",token);
  21. try{
  22. JWTUtils.verify(token);//验证令牌
  23. return true;
  24. }catch (SignatureVerificationException e){
  25. e.printStackTrace();
  26. map.put("msg","无效签名");
  27. }catch (TokenExpiredException e){
  28. e.printStackTrace();
  29. map.put("msg","token过期");
  30. }catch (AlgorithmMismatchException e){
  31. e.printStackTrace();
  32. map.put("msg","算法不一致");
  33. }catch (Exception e){
  34. e.printStackTrace();
  35. map.put("msg","token无效");
  36. }
  37. map.put("state",false);
  38. //将map转为json
  39. String json = new ObjectMapper().writeValueAsString(map);
  40. response.setContentType("application/json;charset=UTF-8");
  41. response.getWriter().println(json);
  42. return false;
  43. }
  44. }

将拦截器添加到spring管理:

  1. package com.zym.springboot_jwt.config;
  2. import com.zym.springboot_jwt.interceptor.JWTInterceptor;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. @Configuration
  7. public class InterceptorConfig implements WebMvcConfigurer {
  8. @Override
  9. public void addInterceptors(InterceptorRegistry registry) {
  10. registry.addInterceptor(new JWTInterceptor())
  11. .addPathPatterns("/user/test") //真实的环境应该为登录放行,其他拦截
  12. .excludePathPatterns("/user/login");
  13. }
  14. }

修改controller

  1. @PostMapping("/user/test")
  2. public String test(){
  3. return "success";
  4. }

测试:

没用token时,直接测试接口:
1.png
生成一个token再测试:
2.png
怎么样,是不是比之前每个接口都验证一次来的自然简便呢?当然,这些只是最简单的整合jwt的demo,真实的情况比这个复杂的多,整合springsecurity后,token的payload里面还要封装权限,token还要设置到redis中,以后会出一篇springsecurity+jwt+springboot整合的权限安全控制!