Reputation: 12621
I followed this railcasts tutorial on how to implement Omniauth-identity but hit a snag.
When I try to register the user the following error pops up
ActionController::InvalidAuthenticityToken in SessionsController#create
In the console logs the following error pops up
Processing by SessionsController#create as HTML
Parameters: {"name"=>"asdasd asdasd", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "provider"=>"identity"}
Can't verify CSRF token authenticity
The user is inserted in the Identity model without problems but when the application tries to create a session it is all for naught.
Here is the relevant code I am using
Gemfile
gem 'bcrypt-ruby', '~> 3.1.2'
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-identity'
initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET']
provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
provider :identity
end
routes
get 'auth/:provider/callback', to: 'sessions#create'
post 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessions#destroy', as: 'signout'
SessionsController
def create
user = User.from_omniauth(env['omniauth.auth'])
session[:user_id] = user.id
redirect_to root_url, notice: "Signed In!"
end
Users model
def self.from_omniauth(auth)
find_by_provider_and_uid(auth["provider"], auth["uid"]) || create_with_omniauth(auth)
end
Upvotes: 4
Views: 5316
Reputation: 61
This solved my problem.
Quoting as it is from the source:
I just spent quite some time debugging this. In my case, I was following an auth0 tutorial that instructed to generate a link with <%= button_to "Login", "auth/auth0", method: :post %>. I was banging my head to a wall for a long time because of the InvalidAuthenticityToken exception.
Turns out that the path had to be "/auth/auth0" (slash in the beginning) for rails to correctly compare the path. Shrug. Maybe this helps someone else. Not sure if this is actually a Rails bug.. it seems at least little unfriendly.
Upvotes: 1
Reputation: 44360
The error InvalidAuthenticityToken
raised when Rails check the CSRF
token, you can disable CSRF
protection on controller by skipping the verification skip_before_action
, add to the top of your SessionsController
:
skip_before_action :verify_authenticity_token, only: :create
But you must be careful and read all about the CSRF
protection.
Upvotes: 5