小编Vik*_*ode的帖子

ng2从cookie获取csrf令牌将其作为标题发布

在花了整整两天的时间搜索网络并阅读文档和大量面临同样问题的人的开放性问题之后,我仍然不了解Angular 2如何处理(x-origin)cookie以及如何访问它们.

问题是: 后端发送了2个带有x-csrf-token和JSESSIONID的cookie.我的工作是将csrf令牌保留在内存中(ng2)并将其(仅)作为标题(不是cookie)发送回每个帖子到后端.

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
Run Code Online (Sandbox Code Playgroud)

我的部分解决方案: 我创建了一个扩展BaseRequestOptions的自定义RequesstOptions类.添加了一些额外的标头,并将'withCredentials'设置为true.

export class MyRequestOptions extends BaseRequestOptions {

  headers: Headers = new Headers({
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  });

  withCredentials = true;
}
Run Code Online (Sandbox Code Playgroud)

在我的HttpService中我做了帖子并得到如下:

@Injectable()
export class HttpService {

  constructor(
    protected _http: Http,
    protected requestOptions: RequestOptions
  ) …
Run Code Online (Sandbox Code Playgroud)

cookies csrf angular

7
推荐指数
1
解决办法
9913
查看次数

标签 统计

angular ×1

cookies ×1

csrf ×1