HTTPS for Rails Application - InvalidAuthenticityToken
Asked Answered
H

1

7

I am trying to get https to work for my rails application. When i try to do any post related activity on the application i am getting the following error.

Exception `ActionController::InvalidAuthenticityToken' at /usr/local/rvm/gems/ruby-2.4.1/gems/actionpack-5.0.4/lib/action_controller/metal/request_forgery_protection.rb:195 - ActionCon
troller::InvalidAuthenticityToken
Exception `ActionController::InvalidAuthenticityToken' at /usr/local/rvm/gems/ruby-2.4.1/gems/actionpack-5.0.4/lib/action_controller/metal/rescue.rb:23 - ActionController::InvalidAuthe
nticityToken
Exception `ActionController::InvalidAuthenticityToken' at /usr/local/rvm/gems/ruby-2.4.1/gems/activesupport-5.0.4/lib/active_support/notifications/instrumenter.rb:25 - ActionController
::InvalidAuthenticityToken
Exception `ActionController::InvalidAuthenticityToken' at /usr/local/rvm/gems/ruby-2.4.1/gems/actionpack-5.0.4/lib/action_dispatch/middleware/callbacks.rb:42 - ActionController::Invali
dAuthenticityToken
Exception `ActionController::InvalidAuthenticityToken' at /usr/local/rvm/gems/ruby-2.4.1/gems/actionpack-5.0.4/lib/action_dispatch/middleware/debug_exceptions.rb:77 - ActionController:
:InvalidAuthenticityToken
Hid answered 17/10, 2017 at 15:5 Comment(5)
Can you post a copy of your controller code? Are you using any authentication gems such as Devise? If so, which version? Also, does this work without SSL?Viyella
@TomAranda it works perfect with http. when i post its getting posted to http on form submission from httpsHid
Is your entire session on https? In other words, are all of your requests to load the form GET and to post the form over https? If not, perhaps rails is using different sessions that that is causing the authenticity token to fail.Viyella
@TomAranda yes looks like it. Any idea how to make sure all of it is on https?Hid
I'll post an answer.Viyella
V
9

Try adding this to your config/environments/production.rb:

# config/environments/production.rb
Rails.application.configure do
  config.force_ssl = true
end

If you want this to take effect in the other environments, add it to the appropriate environment file as well.

Viyella answered 17/10, 2017 at 15:53 Comment(4)
Let me test this out :)Hid
Awesome this works. Had to add proxy_set_header X-Forwarded-Proto $scheme; in nginx config as well :)Hid
Note to these using nginx as a reverse proxy: you'll need to add the line proxy_set_header X-Forwarded-Proto https; to your /sites-available/* file. See this answer.Pepper
For apache, had to add RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME} and also enable the headers module: sudo a2enmod headersLungki

© 2022 - 2024 — McMap. All rights reserved.