Search code examples
ruby-on-railsomniauth

Omniauth-identity InvalidAuthenticityToken


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"=>"asd@yopmail.com", "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

OpenID Authentication

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

Solution

  • 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.