Cross-Origin Resource Sharing with Spring Security

后端 未结 8 1596
暖寄归人
暖寄归人 2020-12-01 04:39

I\'m trying to make CORS play nicely with Spring Security but it\'s not complying. I made the changes described in this article and changing this line in applicationCo

8条回答
  •  余生分开走
    2020-12-01 05:15

    I totally agree with the answer given by Bludream, but I have some remarks:

    I would extend the if clause in the CORS filter with a NULL check on the origin header:

    public class CorsFilter extends OncePerRequestFilter {
    
        private static final String ORIGIN = "Origin";
    
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    
            if (request.getHeader(ORIGIN) == null || request.getHeader(ORIGIN).equals("null")) {
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.addHeader("Access-Control-Max-Age", "10");
    
                String reqHead = request.getHeader("Access-Control-Request-Headers");
    
                if (!StringUtils.isEmpty(reqHead)) {
                    response.addHeader("Access-Control-Allow-Headers", reqHead);
                }
            }
            if (request.getMethod().equals("OPTIONS")) {
                try {
                    response.getWriter().print("OK");
                    response.getWriter().flush();
                } catch (IOException e) {
                e.printStackTrace();
                }
            } else{
                filterChain.doFilter(request, response);
            }
        }
     }
    

    Furthermore, I noticed the following unwanted behavior: If I try to access a REST API with an unauthorized role, Spring security returns me an HTTP status 403: FORBIDDEN and the CORS headers are returned. However, if I use an unknown token, or a token that isn't valid anymore, an HTTP status 401: UNAUTHORIZED is returned WITHOUT CORS headers.

    I managed to make it work by changing the filter configuration in the security XML like this:

    
        ...
        //your other configs
        
    
    

    And the following bean for our custom filter:

    
    

提交回复
热议问题