Running Phoenix behind a load balancer

Wondering if someone can help me.

I have an application that is throwing CSRF errors when deployed to EC2 behind a load balancer and cloud front.

If I visit the direct URL assigned by the load balancer the application works 100% but when using the domain name (which is hooked up to cloudfront) or the cloudfront URL we see CSRF issues.

I’ve read that other frameworks require a whitelisting of certain cookies on cloudfront, but as near as I can tell CSRF tokens are passed in the body of the request (I’ve inspected the requests and they are being sent fine). But I’m clearly missing some step.

Any help would be appreciated.

Is the error you’re seeing?

InvalidCSRFTokenError: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid ‘_csrf_token’ param or ‘x-csrf-token’ header

The tokens are passed in the body (or in a header depending on your CSRF plug config), but they are checked against the token in session data which could be stored in the cookie (depending on your session plug config). I’m wondering if there is a maybe an issue with the cookie domain being correct from behind the load balancer? The token should be added to the session on the same request in which its added to the page, so I think that would only matter if the initial GET request was to a different host than the POST is going to.

In your endpoint.ex you should be able to see the key being used for the cookie, that would probably be what you’d need to whitelist. If you are using a different session storage engine other then :cookie that could be an issue with multiple hosts behind the loadbalancer. For example, if you were using :ets then that would mean the session info is kept in an ets table per-machine rather than embedded in the cookie itself, so you would lose session data between hosts.

3 Likes

Thanks for this @kylethebaker – I’m going to try whitelisting the cookie specified in endpoint.ex now

InvalidCSRFTokenError: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid ‘_csrf_token’ param or ‘x-csrf-token’ header

Is indeed the error I’m seeing.

Update

You’re a star, fixed it :slight_smile:

1 Like