I am working on a Spring Boot application. I have setup a login API (/api/v1/auth
) that can be accessed without authentication and the rest of the APIs (e.g. /api/v1/test
) need authentication.
The auth api works without any errors, but when I call the test API, I get the following error message:
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/test' from 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.
I believe something is missing in my getSecurityFilterChain
. Can someone please help me figure it out?
My security configuration class looks like this:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain getSecurityFilterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers(new AntPathRequestMatcher("/api/v1/auth/**"))
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowCredentials(false);
}
};
}
}
I went through several questions on StackOverflow and some blogs and most of them recommend addition of addCorsMappings
which I already have in my code. Note that I don't get CORS error for the API that doesn't need authentication (/api/v1/auth
). I get CORS errors for all the APIs that need authentication.