InvalidAuthenticityToken and you

While testing logins on my Rails app, I’ve started hitting a lot of InvalidAuthenticityToken errors which were quite bothering…

ActionController::InvalidAuthenticityToken in DeviseInvitable::RegistrationsController#create

Every endpoint I tried resulted in the IAT error, and everywhere I looked were horrible answers such as “disable security for this method”, “disable security for that method”, so on and so forth. In between the plethora of suggested exploitation vectors, I’ve found an incorrect answer on StackOverflow, that lead me to the true gold.

Chances are that if you’re using Rails 6 with Devise, most of the configurations are correct and safe by default, which probably means that just like me you’re using a reverse proxy for caching and SSL wrapping. As it turns out, without the proper additional parameters forwarded by Nginx, Rails will return IAT every single time even when all parameters are set. Your tipical configuration:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http<s>://<ip>:<port>$request_uri;

How it should look:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port 443;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http<s>://<ip>:<port>$request_uri;

With the addition of the -Ssl, -Host, -Port and -Proto parameters everything works correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *