I've tried to add a simple CorsRegistry in a SpringBoot application. I've followed the answer from The Gilbert Arenas Dagger in the question Spring Boot Security CORS, using Option 1. However, I generate still a CORS error when trying to reach my backend using React. Using Postman, everything works just as intended, so I know there must be some miss in my configuration, I just can't seem to find it.
My security config file:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http .cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers("/iotd").hasRole("USER")
.anyRequest().authenticated();
}
}
My CorsConfig file
@Configuration
public class CorsConfig {
private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("CORS implemented");
registry.addMapping("/**")
.allowedMethods("GET", "POST")
.allowedHeaders("*")
.allowedOrigins("*");
}
};
}
}
Upon launch, the logger is triggered and says that the CORS registry is implemented.
I did then follow the second option from his answer, using a CorsConfigurationBean, but the problem persists.
I followed this up with a Filter method, but even when applying the filter before the rest of the securityconfigs, the problem persisted.
OPTIONSmethod in allowedMethods which is sent by client browser for security purpose and try again.