问题造成原因:
在OPTIONS请求中,不会携带请求头的参数,导致SaInterceptor中如 StpUtil.checkLogin() 等鉴权操作无法读取到token而错误拦截请求。
解决思路:
在Interceptor之前的Filter过滤器中检测到OPTIONS请求直接返回成功。
代码:
Filter
@Configuration
@WebFilter(urlPatterns = "/**")
public class FilterConfig implements Filter {
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
httpResponse.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有跨域地址
httpResponse.setHeader("Access-Control-Allow-Headers", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "*");
httpResponse.addHeader("Access-Control-Max-Age", "3600");
if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) {
httpResponse.setStatus(200);
return;
}
filterChain.doFilter(servletRequest, httpResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
Interceptor
@EnableWebMvc
@Configuration
public class RouteInterceptorConfig implements WebMvcConfigurer {
/**
* 注册 Sa-Token 拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SaInterceptor(handler -> {
StpUtil.checkLogin();
}))
.addPathPatterns("/**")
.excludePathPatterns(
"/login",
"/signUp",
);
}
/**
* 注册跨域信息
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 允许所有跨域地址
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(3600);
}
}