首页 > 解决方案 > 从原始反应应用程序访问“http://localhost:8000/oauth/token”处的 XMLHttpRequest 已被 CORS 阻止

问题描述

我在 springboot 中为服务器端使用 oauth2,在客户端使用 React 应用程序。我正在将 grant_type 的令牌请求发送client_credentials/oauth/tokenreact 应用程序并得到上述错误。

我已经使用@CrossOrigin并且也使用 http.cors() 进行全局安全配置,但仍然在浏览器控制台中看到 Preflight cors block 错误。

错误:

从源“http://localhost:3000”访问“http://localhost:8000/oauth/token”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:未通过具有 HTTP 正常状态。xhr.js:177 POST http://localhost:8000/oauth/token net::ERR_FAILED

标签: reactjsspring-bootspring-securityoauth-2.0spring-security-oauth2

解决方案


我认为错误的主要原因已经在错误本身中突出显示。

对预检请求的响应未通过访问控制检查。

这意味着 Spring Security 在预检请求的图片中,并且预检请求不包含有关身份验证的任何信息,因此 Spring Security 将此请求视为来自未经身份验证的客户端,因此拒绝它。

您必须确保首先处理 CORS,您可以通过使用 CorsFilter 来实现这一点。您可以通过使用以下内容提供 CorsConfigurationSource 来将 CorsFilter 与 Spring Security 一起使用

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // You can restrict the origin and method in the following stmt according to the requirement
        configuration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

推荐阅读