gpt4 book ai didi

java - 为什么 Spring Security 身份验证会导致 CORS 错误

转载 作者:行者123 更新时间:2023-12-01 19:43:32 26 4
gpt4 key购买 nike

我有一个用 Java 制作的后端服务器,带有 Spring Boot、Security 和 Web,还有一个用 Angular 制作的客户端。

目前我正在尝试在 localhost:8080/resource 下发出一个简单的请求。

该地址的 Controller 如下所示:

@RestController
public class IndexController {
@CrossOrigin
@RequestMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");

return model;
}
}

Angular 客户端(执行请求的部分)是这样的:

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
public title = "Security Client";
public greeting = {};

constructor(private http: HttpClient) {
http.get("http://localhost:8080/resource").subscribe(data => this.greeting = data);
}
}

仅使用显示的内容会出现 CORS 错误。

是否从我的 pom.xml 中删除 Spring Security 或添加此配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/resource").permitAll();
}
}

解决问题。

我想知道为什么在访问需要用户身份验证的地址时收到 CORS 错误而不是 401 Unauthorized。

最佳答案

根据 Spring Boot 文档:

For security reasons, browsers prohibit AJAX calls to resources outside the current origin. For example, you could have your bank account in one tab and evil.com in another. Scripts from evil.com should not be able to make AJAX requests to your bank API with your credentials — for example withdrawing money from your account!

Cross-Origin Resource Sharing (CORS) is a W3C specification implemented by most browsers that lets you specify what kind of cross-domain requests are authorized, rather than using less secure and less powerful workarounds based on IFRAME or JSONP.

您收到此错误是因为您需要在安全配置中添加过滤器。在您的配置中,添加:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests().antMatchers("/resource").permitAll();
}

在同一个文件中,您应该添加:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH",
"DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type",
"x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);

return source;
}

这对我来说效果很好。

关于java - 为什么 Spring Security 身份验证会导致 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54451030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com