1

After I press the button to "sign in" on https://myapp.com/users/sign_in, the following error appears:

ActionController::InvalidAuthenticityToken in Devise::SessionsController#create

regardless of the existing user's credentials.

If I press the button to sign in on http://myapp.com/users/sign_in, the user signs in and the application seems to work smoothly, except the user cannot create posts under HTTPs too.

I want to make devise authentication work under SSL.

routes.rb:

devise_for :users

application_controller.rb:

class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
end

user.rb:

class User < ApplicationRecord
    devise :database_authenticatable, :recoverable, :rememberable, :registerable, :trackable, :validatable
end
  1. I have the <%= csrf_meta_tags %> in the head
  2. I cleared the cookies in browsers
  3. I tried protect_from_forgery with: :null_session instead of protect_from_forgery with: :exception in app/controllers/application_controller.rb
  4. I tried to put <%= hidden_field_tag :authenticity_token, form_authenticity_token %> in the form_for for new session
  5. I tried devise_for :users, :controllers => { :sessions => "users/sessions" } in root
  6. I tried to add

    config.to_prepare { Devise::SessionsController.force_ssl }
    config.to_prepare { Devise::RegistrationsController.force_ssl }
    config.to_prepare { Devise::PasswordsController.force_ssl }
    

    in config/environments/production.rb

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Bexultan Myrzatay
  • 1,105
  • 10
  • 17

2 Answers2

0

put one line in sessions_controller

skip_before_action :verify_authenticity_token

and in routes.rb

devise_for :users, controllers:
                  {
                    sessions: 'users/sessions',
                  }

because its not require authentication_token when user login

0

There is the workaround of disabling CSRF protection for the sign_in action in the application controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  ....
end

Set it as:

class ApplicationController < ActionController::Base
  protect_from_forgery  with: :exception
  skip_before_filter :verify_authenticity_token, if: -> { controller_name == 'sessions' && action_name == 'create' }
  ...
end