【发布时间】:2021-03-15 21:15:48
【问题描述】:
我正在使用 Spring 框架开发后端。我的前端是使用 Angular 框架编写的。我的 GET 请求被 CORS 政策阻止。
当我使用以下角度函数向 GET 资源发出请求时:
authenticate(credentials, callback) {
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
this.http.get("http://localhost:8080/user", {headers: headers}).subscribe(response => {
console.log(response);
console.log(this.authenticated);
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
return callback && callback();
});
}
我在“网络”选项卡中收到失败的请求。根据我的安全配置,我有时也会收到 401,但在这两种情况下,我都会在控制台中收到“被 cors 阻止”消息。
这是请求被发送到的控制器:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class AuthorizationController {
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/user")
public Principal user(Principal user) {
System.out.println(user);
return user;
}
}
这是我的 Spring 安全配置:
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.httpBasic()
.and().authorizeRequests().antMatchers("/**").permitAll()
.anyRequest().authenticated();
}
注意:这不是我的首选配置。我正在使用它,因为这是我获得工作的唯一方法。使用此配置,我的 POST 请求正在运行。但是,我之前描述的 GET 请求不适用于此配置。
如有任何提示或帮助,我们将不胜感激,如果您需要有关我的代码的更多信息,请告诉我。
【问题讨论】:
标签: angular spring spring-security angular-httpclient