美文网首页
Spring Security处理跨域

Spring Security处理跨域

作者: 湘西刺客王胡子 | 来源:发表于2021-04-27 18:28 被阅读0次

    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);
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring Security处理跨域

          本文链接:https://www.haomeiwen.com/subject/yujprltx.html