SpringBoot实现token校验,能够经过Filter或者HandlerInterceptor,两种方式均可以,Filter在最外层,请求首先会经过Filter,filter容许请求才会经过Intercept。前端
下面以HandlerInterceptor实现为例vue
1.实现HandlerInterceptor,拦截请求校验tokensegmentfault
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添加以下代码:ide
if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { return true; }
对于options的请求不进行token检测便可post