Response for preflight has invalid HTTP status code 401 - Spring

This could be very late but this could solve some ones problem, after long hours i found the answer

public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure( WebSecurity web ) throws Exception
    {
        web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
    }
}

Refer https://stackoverflow.com/a/45830981/3724760


avoid filtering and set status 200 when http method is OPTIONS

if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
    response.setStatus(HttpServletResponse.SC_OK);
} else {
    chain.doFilter(req, res);
}

If there is anyone getting into the similar situation working around with Spring Boot, Spring Security and clients like angular 2/4, I've posted the findings here.

For those who are looking for a short answer, you have to configure two things:

  1. With Spring Boot, the recommended way to enable global CORS is to declare within Spring MVC and combined with fine-grained @CrossOrigin configuration as:

    @Configuration
    public class CorsConfig {
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
                            .allowedHeaders("*");
                }
            };
        }
    }
    
  2. Then, while working with Spring Security, you have to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level as:

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()...
        }
    }
    

Cheers!!!