【发布时间】:2019-06-24 08:24:21
【问题描述】:
我有一个用 Java 制作的带有 Spring Boot、Security 和 Web 的后端服务器和一个用 Angular 制作的客户端。
目前我正在尝试在localhost:8080/resource 下提出一个简单的请求。
该地址的控制器如下所示:
@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。
【问题讨论】:
标签: java spring spring-security cors