乐趣区

SpringBoot JWT Token 跨域 Preflight response is not successful

一、Springboot 实现 token 校验
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();
}
}

二、前端调用 跨域 Preflight response is not successful
通过单元测试、PostMan 测试都可以调同,但是 vue 前端怎么都无法调用,错误如下:

参考 https://segmentfault.com/a/11… 发现是浏览器发出的 OPTIONS 预检请求被 HandlerInterceptor 拦截了,因此在 HandlerInterceptor 添加如下代码:
if (“OPTIONS”.equalsIgnoreCase(httpServletRequest.getMethod())) {
return true;
}
对于 options 的请求不进行 token 检测即可

退出移动版