SpringBoot2 + Spring security CORS OPTIONS method return 401 code

Viewed 1784

I use Angular + Spring Boot2 + Spring Security. I created WebMvcConfigurer config for allow CORS:

@Component
@Profile("dev")
class DevWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedMethods(ALL);
        registry.addMapping("/oauth/token").allowedMethods(ALL);
    }
}

And create security config:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                .antMatchers("/login", "/security/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().csrf().disable();
    }
}

But, When I try make request from angular:

Request URL: http://localhost:8080/oauth/token
Request Method: OPTIONS
Status Code: 401 

I get 401 error code. How can I fix this? All the examples I've found boil down to writing a filter like this:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

But this is some kind of shit. We set the status for all OPTIONS requests that everything is OK. What is it?

My DevWebMvcConfigurer is created only when the profile is dev. How do I add OPTIONS requests permission to it?

1 Answers

You should add /oauth/token to the config.

        http.cors().and().authorizeRequests()
                // add the "/oauth/token" permitAll
                .antMatchers("/login", "/security/**","/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().csrf().disable();
Related