Search code examples
angularhttpcookiessetcookiehttpcookie

Browser won't store cookie


I'm running an angular 4 client on localhost:3000, which is communicating with a WEB API localhost:5000. My problem is, that I can't figure out why the browser refuses to store a cookie, when the server instructs it to do so.

Client Request Headers

Request URL:https://local.dev:5000/user/list?page=1&column=Email&listOrder=2
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:5000
Referrer Policy:no-referrer-when-downgrade
Accept:application/json
Accept-Encoding:gzip, deflate, br
Accept-Language:en-NZ,en-GB;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:0
Content-Type:application/json
DNT:1
Host:local.dev:5000
Origin:https://localhost:3000
Pragma:no-cache
Referer:https://localhost:3000/user

Server Response Headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:https://localhost:3000
Cache-Control:no-cache
Content-Type:application/json; charset=utf-8
credentials:include
Date:Tue, 09 May 2017 08:22:25 GMT
Expires:-1
Pragma:no-cache
Server:Kestrel
Set-Cookie: <cookiename>=<somedata>; expires=Tue, 09 May 2017 09:22:23 GMT; domain=local.dev; path=/; secure; httponly
Transfer-Encoding:chunked
Vary:Origin
withCredentials:true

As you can see CORS is also enabled. HTTPS is used for transmission. Also tried without setting an expiration date. The cookie's domain is set to local.dev. I also tried with / and localhost.

Afterwards Chrome's debug view does not display the cookie. Just some default angular cookie. Therefore I assume the set-cookie header is ignored for some reason.

chrome debug view. cookie not stored

HELP!


Solution

  • For cross-domain AJAX requests, you need to explicitly specify that cookies should be send with the request, and accepted in the response.

    This is done using the withCredentials flag of the XMLHttpRequest object.

    In Angular, you can set it as an option of the $http service, see also AngularJS withCredentials