1. 手写一个跨域处理Filter
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String orignalHeader = StringUtils.defaultIfBlank(request.getHeader("Origin"), "*");
// 指定本次预检请求的有效期
response.setHeader("Access-Control-Max-Age", "3600");
// 服务器支持的所有头信息字段
response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
response.setHeader("Access-Control-Allow-Origin", orignalHeader);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
if (OPTIONS.matches(request.getMethod())) {
response.setStatus(SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
2. 添加进spring-security模块的过滤器链的头部位置
public class WebMvcConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CorsFilter (), WebAsyncManagerIntegrationFilter.class);
}
}
网友评论