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?
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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With