SpringBoot2 + Spring安全性CORS OPTIONS方法返回401代码

时间:2019-01-06 15:37:49

标签: angular spring spring-security cors spring-security-oauth2

我使用Angular + Spring Boot2 + Spring Security。我为允许WebMvcConfigurer创建了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);
    }
}

并创建安全配置:

@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();
    }
}

但是,当我尝试从angular发出请求时:

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

我得到401错误代码。我怎样才能解决这个问题?我发现的所有示例都归结为编写这样的过滤器:

@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 {
    }
}

但这是一种狗屎。我们将所有OPTIONS请求的状态设置为一切正常。什么事?

仅在个人档案为DevWebMvcConfigurer时创建我的dev。如何添加OPTIONS的请求权限?

1 个答案:

答案 0 :(得分:1)

您应将/oauth/token添加到配置中。

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