6

I have red tons of example how to configure CORS in Java Spring, but it is still not working in project with websockets request. It works with mcv api paths, but my websockets path's returns error:

Failed to load http://localhost:8080/chat/info?t=1537264329515: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.

My WebMvcConfig:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    }
}

Maybe someone had same error or have any solutions how should I solve this error?

Roman Haivaronski
  • 530
  • 2
  • 5
  • 18
PrEto
  • 395
  • 2
  • 7
  • 23
  • @RamanHaivaronski, I am talking about websockets, not rest API. Rest API works in my project. – PrEto Sep 18 '18 at 11:33
  • havent faced this issue yet so dont know much about it and i dont know if my advice is correct or not but just recommending it... did you try using `@crossorigin` annotation anywhere? – Syed Anas Sep 18 '18 at 12:03

4 Answers4

8

If someone will have this question, I solved my problem in WebsocketConfig like this:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:3000").withSockJS();
}
PrEto
  • 395
  • 2
  • 7
  • 23
3

Try this, it worked for me when I had the same problem, possibly not the best practice though:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH")
                .allowedOrigins("*");
    }
    ...
}

add another filter

public class CorsFilter extends OncePerRequestFilter {

static final String ORIGIN = "Origin";

protected void doFilterInternal(
        HttpServletRequest request, 
        HttpServletResponse response, 
        FilterChain filterChain) throws ServletException, IOException {

    String origin = request.getHeader(ORIGIN);

    response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE, PATCH");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");

    if (request.getMethod().equals("OPTIONS"))
        response.setStatus(HttpServletResponse.SC_OK);
    else 
        filterChain.doFilter(request, response);

}

}

and added to the series of my filters:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

...

@Bean
public CorsFilter corsFilter() throws Exception {
    return new CorsFilter();
}
Roman Haivaronski
  • 530
  • 2
  • 5
  • 18
  • Worked for me to solve a similar issue "origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." – LoRe Oct 17 '19 at 14:38
  • @LoRe this never worked for me – Nemuga Dev Mar 24 '21 at 12:23
1

You need to try this one

@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp").setAllowedOrigins("*");
    }
}
Alexander Petrov
  • 951
  • 6
  • 11
0

I'm not sure about MVC, but when I faced this issue(While in development mode in ReactJs), I have used a Chrome Extension: Allow control allow origin, and it fixed the problem.

Ron F
  • 370
  • 2
  • 14
  • But wont this error go to production? If user doesn't use extension? – PrEto Sep 18 '18 at 11:15
  • I'm not sure about it, but it is possible. I have used this extension just for development, in order to check that my code is valid. I suggest that you use it until you finish your product, and than think about global solution. – Ron F Sep 18 '18 at 11:17
  • Thank you for your solution. But I am looking for global solution. – PrEto Sep 18 '18 at 11:19