SpringBoot2 + Spring security CORS OPTIONS方法返回401代码

3

我使用 Angular + Spring Boot2 + Spring Security 技术栈。为了允许跨域请求,我创建了一个名为 WebMvcConfigurer 的配置文件:

@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个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接