JWT整合SpringBoot(拦截器)
1、为什么使用拦截器拦截Token
上个例子我们看到了,每请求一个接口都要验证Token,这样的话就有大量代码冗余
单体应用:用拦截器
分布式应用:在网关中拦截
2、上代码
首先得编写一个拦截器:
package com.zym.springboot_jwt.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zym.springboot_jwt.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求头中的Token
String token = request.getHeader("token");
Map<String,Object> map = new HashMap<>();
log.info("当前Token为[{}]",token);
try{
JWTUtils.verify(token);//验证令牌
return true;
}catch (SignatureVerificationException e){
e.printStackTrace();
map.put("msg","无效签名");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("msg","token过期");
}catch (AlgorithmMismatchException e){
e.printStackTrace();
map.put("msg","算法不一致");
}catch (Exception e){
e.printStackTrace();
map.put("msg","token无效");
}
map.put("state",false);
//将map转为json
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
将拦截器添加到spring管理:
package com.zym.springboot_jwt.config;
import com.zym.springboot_jwt.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/user/test") //真实的环境应该为登录放行,其他拦截
.excludePathPatterns("/user/login");
}
}
修改controller
@PostMapping("/user/test")
public String test(){
return "success";
}
测试:
没用token时,直接测试接口:
生成一个token再测试:
怎么样,是不是比之前每个接口都验证一次来的自然简便呢?当然,这些只是最简单的整合jwt的demo,真实的情况比这个复杂的多,整合springsecurity后,token的payload里面还要封装权限,token还要设置到redis中,以后会出一篇springsecurity+jwt+springboot整合的权限安全控制!