2

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.

1 Answers1

1

Add OPTIONS method in allowedMethods which is sent by browser for security purpose.

This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.

Romil Patel
  • 12,879
  • 7
  • 47
  • 76