How do I ensure CloudFront returns cookies from my Elastic Beanstalk REST API application
Cookies are blocked by default
Making them work requires two changes, in the behavior settings:
- Allowing cookies to pass through (on the request)
- Letting the
Set-Cookie
header come back (with the response)
Where to change cookie settings...
Confused? If so, then...
Here's the step-by-step process...
In your CloudFront distribution:
- Go to the Behaviors tab
- Select the behavior and click Edit
- Find the Cache key and origin requests section
- Under Origin request policy click on Create policy
- Fill in the Name, and then scroll to the bottom and change Cookies from None to All (or Include Specified Cookes, if you want to whitelist)
- Hit Create to save the new policy
- Switch back to the original tab (with the Edit behavior page)
- Find the Cache key and origin requests section again
- Under Response headers policy, tap on Create policy
- Fill in the Name, and then Scroll to the bottom
- Under Custom headers, tap the Add header button
- In the Name field put
Set-Cookie
- Leave Value empty, and Origin override should stay unchecked
- Hit the Create button
- Go back to the Edit behavior page, hit the refresh buttons, so you can pick those two new policies
- Hit Save Changes and give it a few minutes to deploy
You need to forward cookies in the cache behavior. Without it, CloudFront removes the Set-Cookie header from the response.
Here's the documentation:
You can configure each cache behavior to do one of the following:
...
Don’t forward cookies to your origin – CloudFront doesn’t cache your objects based on cookie sent by the viewer. In addition, CloudFront removes cookies before forwarding requests to your origin, and removes Set-Cookie headers from responses before returning responses to your viewers.