Spring Boot JWT CORS with Angular 6

Since message is about your preflight request i.e. OPTIONS request,

I guess, you need to do two things on server side / Spring Boot code ,

  1. Return OK from Authentication filter so need to add below in attemptAuthentication method as first check i.e. don't do real authentication for preflight requests,

if (CorsUtils.isPreFlightRequest(httpServletRequest)) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); return new Authentication() ; //whatever your token implementation class is - return an instance of it
}

CorsUtils is - org.springframework.web.cors.CorsUtils

  1. Let Spring Security Enter Authorized Options requests into System so add these lines in Security Config ,

.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

You can allow unauthorized OPTIONS requests too but I guess , that wouldn't be a good idea. Also, try to narrow down "/**" to specific URLs if possible.


i had the same problem, finally i only added httpRequest.cors(); at the end of configure method in the WebSecurityConfig class and it worked well, the explanation of why is :

explicitly the preflight requests are not excluded from authorization in Spring Security configuration. Remember that Spring Security secures all endpoints by default.

As a result, API expects an authorization token in the OPTIONS request as well.

Spring provides an out of the box solution to exclude OPTIONS requests from authorization checks:

The cors()method will add the Spring-provided CorsFilter to the application context which in turn bypasses the authorization checks for OPTIONS requests.

for all details https://www.baeldung.com/spring-security-cors-preflight