I am using spring boot 2.4.8. I am trying to allow CORS using this code:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
The WebMvcConfigurer
gets called; however, the mapping does not get applied because I have a OncePerRequestFilter
in the project.
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.equals("Bearer testaccesstoken")) {
response.setStatus(401);
return;
}
filterChain.doFilter(request, response);
}
}
If I remove the filter, the CORS works just fine. I attached a sample app reproducing the issue. demo.zip
Comment From: wilkinsona
@ShaimaaSabry Thanks for the sample. Unfortunately, it's not clear to me how it should be used to reproduce the problem. There's no test that reproduces a failure and I couldn't find any instructions describing some manual steps either. Can you please either add a test or describe the steps to take to reproduce the problem?
Also, I notice that you're using @EnableWebMvc
. You almost certainly don't want to do that in a Spring Boot application as it switches off the auto-configuration of Spring MVC.
Comment From: ShaimaaSabry
@wilkinsona I am using an Angular app that access this spring boot api app. I am getting this CORS error in my Angular app:
Access to XMLHttpRequest at 'http://localhost:8080/authors' from origin 'http://localhost:4200' 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.
Using @EnableWebMvc
was the solution I found in order to allow cross origin request. If it's not recommended to use it in a spring boot application, can you please advice on what I should use instead to allow cross origin requests?
Comment From: wilkinsona
Thanks, but there's no controller in your app that handles /authors
so, unfortunately, I'm no closer to understanding the problem that you're reporting. If you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem.
can you please advice on what I should use instead to allow cross origin requests?
As described in the documentation, a WebMvcConfigurer
bean without @EnableWebMvc
should be sufficient.
Comment From: ShaimaaSabry
@wilkinsona Your suggestion worked and solved my problem. Thank you.
Comment From: wilkinsona
Thanks for letting us know.