【发布时间】:2018-08-07 06:05:15
【问题描述】:
我是使用 Angular HttpClient 的新手(也会写英文)
我有一个问题,我正在尝试使用 POST 方法发送 HTTP 请求以协商 OAuth 令牌获取,但 Angular 发送 OPTIONS 请求:
服务:
login(username: string, password: string) {
const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(TOKEN_AUTH_USERNAME + ':' + TOKEN_AUTH_PASSWORD)
})
};
return this.http.post<string>(AuthenticationService.AUTH_TOKEN, body, httpOptions);
结果:
对于我的后端,我使用的是 Spring Security,并添加了一个过滤器以允许 CORS:
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
【问题讨论】:
-
您的身份验证服务器似乎与您的前端应用程序不在同一个域中,并且您面临 CORS(跨域资源共享)问题。
-
您不能使用 XHR 调用
/token端点。它应该从后端或本机应用程序访问。 -
你是否也会从 spring 提供你的 Angular 应用程序,或者用户是否会从其他域下载脚本?
标签: angular spring-security oauth-2.0 angular5 spring-security-oauth2