SpringBoot实现token校验,可以通过Filter或者HandlerInterceptor,两种方式都可以,Filter在最外层,请求首先会通过Filter,filter允许请求才会通过Intercept。
下面以HandlerInterceptor实现为例
1.实现HandlerInterceptor,拦截请求校验token
public class AuthenticationInterceptor implements HandlerInterceptor { private static final String URI_PASS_TOKEN = "/user/login"; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { log.info("authentication interceptor preHandle path:{} uri:{}",httpServletRequest.getServletPath(),httpServletRequest.getRequestURI()); // if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { // return true; // } if (httpServletRequest.getRequestURI().endsWith(URI_PASS_TOKEN)) { return true; } //从http header里面获取token String token = httpServletRequest.getHeader("token"); if (StringUtils.isEmpty(token)) { throw new AuthenticationException(CODE_AUTHENTICATION_FAILED,"token is empty"); } Algorithm algorithm = Algorithm.HMAC256(JwtConstant.TOKEN_CREATE_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); try { verifier.verify(token); }catch (Exception ex){ throw new AuthenticationException(CODE_AUTHENTICATION_FAILED,ex.getMessage()); } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
2.Configuration配置,实现自动注入
@Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor()) .addPathPatterns("/**"); } @Bean public AuthenticationInterceptor authenticationInterceptor() { return new AuthenticationInterceptor(); } }
通过单元测试、PostMan测试都可以调同,但是vue前端怎么都无法调用,错误如下:
参考 https://segmentfault.com/a/11...
发现是浏览器发出的OPTIONS预检请求被HandlerInterceptor拦截了,因此在HandlerInterceptor添加如下代码:
if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { return true; }
对于options的请求不进行token检测即可