Ad

Spring BOOT Cors Filter OPTIONS Error 'Response To Preflight Request Doesn't Pass Access Control Check'

- 1 answer

I have been trying to solve this cors error for hours and I tried every possible solution except one (which is adding options method for every resource/request).. You can find every tried things below;

Cors-Configuration Class

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
    return new WebMvcConfigurer()  {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedHeaders("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true)
                    .allowedOrigins("*")
                    .exposedHeaders(AuthorizationController.AUTHENTICATION_KEY_NAME + "," +
                                    HandlerHelper.REASON_KEYNAME)
                    .maxAge(3600);
        }
     };
    }


}

Pre Handle

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Origin","*");
    response.setHeader("Access-Control-Allow-Methods" ,"GET, POST, PUT, DELETE, OPTIONS");
    response.setHeader("Access-Control-Allow-Headers",AuthorizationController.AUTHENTICATION_KEY_NAME +","+ REASON_KEYNAME);
    response.setHeader("Access-Control-Max-Age","3600"); }

application.properties

spring.mvc.dispatch-options-request=true

Adding both annotation to class and OPTIONS method to any request per resource

 @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
        public ResponseEntity handle() {
            return new ResponseEntity(HttpStatus.OK);
        }

How can i allow 'not simple cors request' in spring boot? Or is this react issue? My front-end developer cant send request from axios..

Ad

Answer

Adding code below fixed the problem.

@EnableWebSecurity
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        http.cors().and().csrf().disable();
    }
}
Ad
source: stackoverflow.com
Ad