Search code examples
subdomainruby-on-rails-5csrf

Rails5 "Can't verify CSRF token authenticity" issue with subdomain in production environment


I have a subdomain:

https://admin.mysite.com

In my production environment when I sign in using devise form, I get error "Cant verify CSRF token authenticity".

I did a lot of research on google and got to know that I need to make a change in initializers/session_store.rb. My default session_store.rb file contains:

Rails.application.config.session_store :cookie_store, key: '_myapp_session'

Someone said that :domain should be set to ".mysite.com" and some set that it should be :all. I had tried all combinations including tld options as well but I was still getting that error.

:cookie_store,
{
  :key => '_myapp_session',
  :domain => :all, # :all defaults to da tld length of 1, '.web' has length of 1
  :tld_length => 2 # Top Level Domain (tld) length -> '*.myapp.web' has a length of 2
}

Please help, thanks.


Solution

  • After trying alot of combinations it turned out that I had to include ssl setting in my nginx file and didn't need to change session_store.rb at all.

    I had added following line in my nginx file and everything seemed to be working fine.

    proxy_set_header X-Forwarded-Ssl on;
    

    Note: If you have many specific domains and that your application requirement is complex then you might have to change this file but in my case I had just this subdomain and not even a main domain handling my site, I was ok with it. In my case Rails5 automatically handled it and I didn't need to change anything in my app except that SSL setting in my nginx file.

    I hope this will help someone else, :).