在花费了整整2天的时间在网上搜索、阅读文档和大量开放性问题后,我仍然不明白Angular 2如何处理(x-origin) cookie以及如何访问它们。
问题:后端将两个cookie发送到前端,其中包含x-csrf-token和JSESSIONID。我的工作是在内存中保留csrf令牌(ng2),并且将其作为标头 (而不是cookie) 与每个post请求一起发送回后端。
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Access-Control-Allow-Origin,Access-Control-Allow-Credentials
Set-Cookie: x-csrf-token=8555257a-396f-43ac-8587-c6d489e76026; Path=/app
Set-Cookie: JSESSIONID=73E38392C60370E38FBAF80143ECE212; Path=/app/; HttpOnly
Expires: Thu, 12 Apr 2018 07:49:02 GMT
Cache-Control: max-age=31536000
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 12 Apr 2017 07:49:02 GMT
我的部分解决方案: 我创建了一个自定义的RequestOptions类,它继承了BaseRequestOptions。添加了一些额外的头部信息,并将'withCredentials'设置为true。
export class MyRequestOptions extends BaseRequestOptions {
headers: Headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json',
});
withCredentials = true;
}
在我的 HttpService 中,我这样进行 post 和 get 请求:
@Injectable()
export class HttpService {
constructor(
protected _http: Http,
protected requestOptions: RequestOptions
) { }
get(url): Observable<any> {
return this._http.get(url, this.requestOptions).map( res => res.json() );
}
post(url: string, object: any): Observable<any> {
return this._http.post(url, object, this.requestOptions).map( res => res.json() );
}
}
我在我的app.module中这样做:
providers: [
{ provide: RequestOptions, useClass: DocumentumDefaultRequestOptions },
{ provide: XSRFStrategy, useFactory: xsrfFactory }
],
我的xsrfFactory
export function xsrfFactory() {
return new CookieXSRFStrategy('x-csrf-token', 'x-csrf-token');
}
我的部分结果: 此时Angular会在每个请求中发送一个Cookie(不区分GET和POST),其中包含jsessionid和x-csrf-token,形如:
POST /app/business-objects/business-objects-type HTTP/1.1
Host: localhost:8040
Connection: keep-alive
Content-Length: 26
Pragma: no-cache
Cache-Control: no-cache
Authorization: Basic ZG1hZG1pbjphZG1pbg==
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json
Accept: application/json
Referer: http://localhost:4200/page
Cookie: JSESSIONID=B874C9A170EFC12BEB0EDD4266896F2A; x-csrf-token=0717876e-f402-4a1c-a31a-2d60e48509d3
我的十亿美元问题:
- 我应该在哪里获取 x-csrf-token,并如何将其添加到我的请求中?
CookieXSRFStrategy('x-csrf-token', 'x-csrf-token')
到底是做什么的?我不喜欢文档中对它的解释,能否访问它来获取数据?
在发送 HTTP 请求之前,CookieXSRFStrategy 查找名为 XSRF-TOKEN 的 cookie,并使用该 cookie 的值设置名为 X-XSRF-TOKEN 的头部。
在我的情况下它并没有设置这个头部,但为什么呢?
现在我正在与 sessionid 和 csrf token 一起向后端发送 cookie,但是是 CookieXSRFStrategy 或 "withCredentials" 标志在发送它们呢?
请不要用像 "document.cookie" 这样的一行回答。没有元数据的数据是无用的。
x-csrf-token
cookie是由后端与文档一起发送还是与ajax GET请求一起发送的? - n00dl3document.cookie
返回什么? - n00dl3