Invalid CORS request in Spring

I am trying to enable specific IP addresses to access a specific method.

@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/updateDetail") .allowedOrigins("127.0.0.1", "10.96.33.45") .allowedMethods("GET", "POST"); } 

But when I try to call the same method, I get an invalid CORS request. Can anyone help me with this?

+6
source share
2 answers

"Invalid CORS request" is returned by org.springframework.web.cors.DefaultCorsProcessor when

  1. Spring is configured to use CORS and
  2. the browser sends the "Origin" header with the request and it does not match the domain / port / scheme of your server and
  3. the response does not have an Access-Control-Allow-Origin header and
  4. the request is not a preflight request.

If you don't need CORS, call cors().disable() in your implementation of WebSecurityConfigurerAdapter # configure (HttpSecurity http) (there may be other ways to do this, for example if you use Spring Boot).

Or you can add the header "Access-Control-Allow-Origin" to your answers using, for example, org.springframework.web.cors.CorsConfiguration or addCorsMappings (as you did, but maybe you should add more methods, or URLs or IP do not match?).

0
source

This class is what you are looking for:

 @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class SimpleCorsFilter implements Filter { public SimpleCorsFilter() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "12000"); response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); response.setHeader("Access-Control-Expose-Headers", "*"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } } 

This filter will solve all your core problems.

0
source

Source: https://habr.com/ru/post/1262629/


All Articles