reactjs - 从原始反应应用程序访问“http://localhost:8000/oauth/token”处的 XMLHttpRequest 已被 CORS 阻止
问题描述
我在 springboot 中为服务器端使用 oauth2,在客户端使用 React 应用程序。我正在将 grant_type 的令牌请求发送client_credentials
到/oauth/token
react 应用程序并得到上述错误。
我已经使用@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
解决方案
我认为错误的主要原因已经在错误本身中突出显示。
对预检请求的响应未通过访问控制检查。
这意味着 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;
}
}
推荐阅读
- android - 在 Kotlin 中处理异常的正确方法是什么?
- excel - 将excel函数分配给Excel VBA中的变量
- c - 用多线程 C 分叉一个进程
- wordpress - Woocommerce Membership API - 获取受限内容
- windows - 从 WSL2 内部访问在 Windows 中运行的本地主机?
- python - 用 selenium 定位元素后,你可以追溯/报告元素的 xpath 吗?
- oracle - 我可以使用 ansible 备份 Oracle 和 Hana 数据库吗?
- powerbi - 计算滚动平均值并用于缺失值
- charts - 为什么 Primefaces donutChart 不起作用?
- webrtc - WebRTC中TURN服务器和SFU的区别?