CORS allowed-origin restrictions aren’t causing the server to reject requests

后端 未结 3 462
天命终不由人
天命终不由人 2020-11-27 08:43

I am using Spring Boot v1.5.1, and it seems my restriction on CORS origin is not working.

My application.properties file has the following line (ref1 ref2).

相关标签:
3条回答
  • 2020-11-27 09:05

    Explicitly specifying the domain as string in @CrossOrigin("http://mydomain.io") will work. I dont' think this will work @CrossOrigin("${endpoints.cors.allowed-origins}").

    0 讨论(0)
  • 2020-11-27 09:07

    However, when I open up a browser and type in http://localhost:8080/api/car I am still able to access the REST endpoint.

    CORS allowed-origins settings don’t cause servers to block requests.

    And because the server isn’t blocking the request, that doesn’t prevent you from opening the URL directly in a browser.

    The same-origin policy is what imposes cross-origin restrictions, and the same-origin policy is only applied to frontend JavaScript in web applications running in a web browser, and using XHR or Fetch or jQuery $.ajax(…) or whatever to make cross-origin requests.

    So CORS isn’t a way to cause servers to block requests. And so it also isn’t a way to prevent users from being able to directly navigate to a URL, and isn’t a way to prevent any non-web-application tools like curl or Postman or whatever from accessing the URL.

    0 讨论(0)
  • 2020-11-27 09:18

    As for me I am adding s CrossRef Filter on my apps.

     package com.alexfrndz.filter;
    
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     import org.springframework.stereotype.Component;
     import org.springframework.web.filter.GenericFilterBean;
    
     import javax.servlet.FilterChain;
     import javax.servlet.ServletException;
     import javax.servlet.ServletRequest;
     import javax.servlet.ServletResponse;
     import javax.servlet.http.HttpServletResponse;
     import java.io.IOException;
    
    
     @Component
     public class SimpleCORSFilter extends GenericFilterBean {
    
    /**
     * The Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
    
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, resp);
    
    
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题