没有授权标头将 POST 从 Angular 发送到 Spring
Posted
技术标签:
【中文标题】没有授权标头将 POST 从 Angular 发送到 Spring【英文标题】:No Authorization Header sending POST from Angular to Spring 【发布时间】:2018-11-19 09:13:20 【问题描述】:我有:
用 Spring 编写的后端服务器 和一个用 Angular 编写的客户端我正在尝试发送 POST 请求...
import Injectable from '@angular/core';
import HttpClient, HttpHeaders from '@angular/common/http';
import Observable from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthenticationService
constructor(private http: HttpClient)
login(username: string, password: string)
const httpOptions =
headers: new HttpHeaders(
'Content-Type' : 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'Authorization' : 'Basic blablabla_base64_encoded'
)
;
const body = 'username=' + username + '&password=' + password + '&grant_type=password';
console.log(body);
console.log(httpOptions.headers);
console.log(this.http.post<any>('http://localhost:8080/oauth/token', body, httpOptions));
return this.http.post<any>('http://localhost:8080/oauth/token', body, httpOptions)
.map(
user =>
// login successful if there's a jwt token in the response
if (user && user.token)
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
return user;
);
logout()
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
用我得到的 Wireshark 过滤请求:
OPTIONS /oauth/token HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (Khtml,
like Gecko) Chrome/67.0.3396.79 Safari/537.36
DNT: 1
Access-Control-Request-Headers: authorization
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
WWW-Authenticate: Basic realm="oauth2/client"
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Credentials: true
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Sat, 09 Jun 2018 14:19:36 GMT
由于某种原因,我没有授权标头,并且来自 POST 的请求变成了 OPTIONS。我在网上搜索了几个小时的其他解决方案,但没有一个对我有帮助。
一些建议?
【问题讨论】:
【参考方案1】:找到了这个问题的答案。
Spring 服务器还必须根据此处文档中解释的范例来管理预先发送的请求: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests
要添加 CORS 管理,可以在 Spring Boot 应用程序中实现的所有其他过滤器之前添加一个 CORSFilter,这里有一个很好的代码示例: https://gist.github.com/malike/f8a98b498368932e6d7511886a167848
【讨论】:
以上是关于没有授权标头将 POST 从 Angular 发送到 Spring的主要内容,如果未能解决你的问题,请参考以下文章
ANGULAR 没有向我的特定 Http Post 请求发送标头
无法使用 Angular 7 将授权标头发送到节点 11/Express 4 服务器