设置withcredential = true后未在请求标头中设置Cookie

时间:2018-07-13 14:12:55

标签: angular cookies cors

我在登录后调用api,并在登录响应标头中设置了set-cookie,并在浏览器中设置了cookie。但是当我尝试发出其他请求时,请求标头中没有cookie传递。我尝试添加withcredential = true,并且还允许带有所有必需标头的CORS。 在浏览器中在登录响应中设置Cookie

.AspNetCore.Identity.Application    
expires 2018-07-27T14:26:34.000Z
httpOnly    true
path    /
secure  true
value   CfDJ8IpQ2KMnnJJCu-Bxqp-xHNOQGuT6Ig74z_z6fhAba0WGCMyq7er9Zo87dX36mvr3vHm827XQFM_8cNQiv811mitpYZ4rRVRp4iV3RfpDkqGL-4UizEGUkJfSxxkFzIbVEEJNwIJXf5iFFlbC7Fw8zKDn7DYJN70iniH4HE-bzqJ4KXSsKnCyqePsYyi6iJ0_Rkk_TiE-TXggnFqrU_8n5XPcYaRVeinAeHRZ2xmJbcVrOwFAV1-D8zwgpnJxs2WaLsM9h5IoqdV1wOwyT-Awoy0QqAtTiUPs5h5Gh52HubsBcWLPKE_FbzfmK_1HsDGH1e1PIHYJaIgLx-q0trTSGK-22wvOnqMipax94zoO6mfF2Pbrz7NM-eJBBCTkSoNYXVIj8EpRPJXhk8uLKC9rqon2hA4qHpnrUWWdz1LT7FYzHjnhAx3hctXr2laQgc3ipT410zI15tl5XIIjEbqr9D5E6o-4MkcSCLsHCLkaurSmoQWF2VRQ8OuVHFz6Z7XTu7myAsCFWf3INcV-WBtJY6l9Luk2D7uenofPGFZ8D4fDL0oaPqvAKve6N8r2Q_eDXEVf-

查看我的代码

Request header from browser console
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate, br
Accept-Language en-US,en;q=0.5
Access-Control-Allow-Credentials    true
Connection  keep-alive
Content-Length  27
Content-Type    application/x-www-form-urlencoded
Host    localhost:44354
Origin  http://localhost:4200
Referer http://localhost:4200/changepassword
User-Agent  Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0
withCredentials true

我的代码:-

changePassword(changePasswordModel: ChangePassword): Observable<ApiResponse> {
    const body = JSON.stringify(changePasswordModel)

     let enco : any = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('withCredentials', 'true')
        .set('Access-Control-Allow-Credentials', 'true');

    return this._httpClient.post(this.identityAPIEndPoint + 'Account/ChangePassword', body, { headers: enco, withCredentials: true}).pipe(
      map((response: Response) => <ApiResponse>response.json()));
  }

我正在将Angular 5与HttpClient用于发布请求。 我是使命吗? 请给我提示。

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您的Cookie的scope。有关更多信息,请参见Scope of cookies部分here

因此,您应该为所有页面设置相同的path,以便cookie在所有页面上都可用。例如,您可以将path设置为/或应用程序的基本路径。

Access-Control-Allow-Credentials是一个响应头,因此应在响应中而不是在请求中提供:请参见here

withCredentials选项根本不是HTTP标头,而是应该在options对象中传递的选项:请参见此link

另外,请阅读this文章以了解有关CORS的更多信息。