Search code examples
amazon-web-serviceshttpamazon-s3cookiesamazon-cloudfront

How can you access cookies on a static S3 site behind a CloudFront distribution?


So I'm trying to deploy my website which works well when in a local environment, but when it is deployed to Cloudfront, it can't seem to access cookies.

My frontend tech stack is as follows: Angular site hosted on S3, cloudfront distribution in front of it, custom domain name with a valid ssl certificate.

When the user navigates to the login page, they can successfully submit the forum, and the server responds with a JWT token in the Set-Cookie header.

Set-Cookie header

After this though, in the angular site it says that the access-token cookie does not exist. The strange part here is that on subsequent requests, the access-token cookie is in fact forwarded back to the backend. (In the image below, the login button was pressed again, so the response cookie is the same as the request cookie.)

A screenshot of the token being received and sent through the network.

I've ensured that HttpOnly is not set, and that the frontend and backend are both hosted under the same root domain frontend.root.com and api.root.com.

Cloudfront has been configured to forward the access-token cookie:

cache policy: Cache key settings: headers - none, cookies - none, query strings - none

origin request policy (note that it still did not work when I had this set to forward all cookies and not just the access token): Origin request settings: headers - all viewer headers, cookies - access-token, query strings - all

Response headers settings: CORS settings for response headers

So in my angular site, after the /login api call resolves, I use the ngx-cookie-service to check and try to retrieve the cookie.

this.cookieService.check('access-token'); // checks if it exists, returns false
this.cookieService.get('access-token'); // returns '' meaning the cookie does not exist

Any ideas on how to resolve this issue and access the cookies from within my angular site? I can provide more information on my configurations if needed. Thanks!


Solution

  • As you can barely make out in the screenshot the Cookies have the domain set as something starting with a suggesting that it is api.root.com, most importantly it is not frontend.root.com and not root.com.

    The server needs to set the domain of the cookie to root.com for it to be available to all subdomains of it.