简体   繁体   English

Set-Cookie标头被忽略

[英]Set-Cookie Header Ignored

The csrf cookie sent by my backend seems to be ignored by browsers. 我的后端发送的csrf cookie似乎被浏览器忽略。

请求和回应

The request is being made via Angular (2) from http://localhost.mydomain.com:4200 like so: 该请求是通过Angular(2)从http://localhost.mydomain.com:4200发出的,如下所示:

get() {
  let headers = new Headers({
    'Content-Type'    : 'application/json',
    'withCredentials' : true
  });
  let options = new RequestOptions({headers : headers});
  return this.http.post('https://api.mydomain.com', {
    o : 'csrf',
    m : 'get',
    p : {}
  }, options)
    .map((res: Response) => {
      console.log('response received: ', res)
    })
    .catch((err: any) => {
      console.log('error received: ', err);
      return Observable.throw(err);
    });
}

The request is being received by AWS API Gateway/Lambda running Express 4.x and sent back as: 运行Express 4.x的AWS API Gateway / Lambda接收到该请求,并以以下方式发送回:

res.cookie('csrf', token, {domain : '.mydomain.com'});

Setting cookies on xhr responses should be fine. 在xhr响应上设置cookie应该没问题。 Because both the request and response are subdomains of mydomain.com I shouldn't need the withCredentials option (though, as shown, I tried sending it anyway). 因为请求和响应都是mydomain.com的子域,所以我不需要withCredentials选项(尽管如图所示,我还是尝试发送它)。 The response is received and the header is there. 接收到响应,并且标题在那里。 It's just not being set. 只是没有设置。

It's being ignored in Chrome, Firefox and IE so I'm sure the problem is I'm missing something obvious :) 它在Chrome,Firefox和IE中被忽略,因此我确定问题是我缺少明显的东西:)

For anyone that stumbles on this @robertklep and @charliefl were correct (thanks!). 对于偶然发现此@robertklep和@charliefl的任何人都是正确的(谢谢!)。 The correct way to write my request was: 编写我的请求的正确方法是:

get() {
  let headers = new Headers({
    'Content-Type'    : 'application/json'
  });
  let options = new RequestOptions({
    headers : headers,
    withCredentials: true
  });
  return this.http.post('https://api.mydomain.com', {
    o : 'csrf',
    m : 'get',
    p : {}
  }, options)
    .map((res: Response) => {
      console.log('response received: ', res)
    })
    .catch((err: any) => {
      console.log('error received: ', err);
      return Observable.throw(err);
    });
}

In addition, because I was trying to be lazy and use a wildcard in the 'Access-Control-Allow-Origin' on my server I then ran into the error: 另外,由于我想变得懒惰,并且在服务器的'Access-Control-Allow-Origin'使用通配符,因此我遇到了错误:

 A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

If you have multiple domains consuming your API you'll have to set the 'Access-Control-Allow-Origin' dynamically on your server as discussed here and here depending on what domains/subdomains you want to allow. 如果您有多个使用API​​的域,则必须根据此处此处要讨论的内容,根据要允许的域/子域, 服务器上动态设置'Access-Control-Allow-Origin'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM