Search code examples
ruby-on-railsrubysubdomaincsrf

Rails 5 Invalid Authenticity Token when trying to login from transparently redirected subdomain


I have a Rails 5 app running on port 12003 and I configured a subdomain to transparently redirect to that port as follows:

https://test.example.com => https://example.com:12007

The problem is that when I try to log in or execute an action that requires an Authenticity Token from the subdomain, the application throws this error:

ActionController::InvalidAuthenticityToken in AccessController#attempt_login

The application does not throw it when I try to perform an action from the url that includes the port: http://example.com:12007

This makes me think that the app detects the subdomain as a Forgery attempt.

Is there a way to whitelist the subdomain or fix this isssue without disabling CSRF Protection on my app?


Solution

  • I've encountered similar problem in combination of Rails 5, Devise and Nginx with SSL.

    Simply switching off the CSRF protection resulted in inability to log in/sign in through devise (the session hasn't changed, log in redirected back to root as if nothing happened).

    Using curl I tested that this was issue only on HTTPS, but everything worked well on HTTP.

    The only line that has solved this problem for me in the end of the day was

    server {
      location @app {
        ...
    
        proxy_set_header X-Forwarded-Proto https;
    
        ...
      }
    }
    

    in Nginx site configuration (/etc/nginx/sites-available/default).