Search code examples
ruby-on-railsrubygoogle-oauthomniauth

Could not authenticate you from GoogleOauth2 because "Authenticity error"


Hi I encounter this error in GoogleOauth2 API "Could not authenticate you from GoogleOauth2 because Authenticity error" and "not found, Aunthentication passthru" and cant figure out the problem.

this is my OmniauthCallbacksController

'''

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
   def google_oauth2
        @user = User.from_omniauth(request.env["omniauth.auth"])
        if @user.persisted?
          flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
          # auth = request.env["omniauth.auth"]
          # @user.access_token = auth.credentials.token
          # @user.expires_at = auth.credentials.expires_at
          # @user.refresh_token = auth.credentials.refresh_token
          # @user.save!
          sign_in @user, event: :authentication
          redirect_to tasks_path
        else
          session["devise.google_data"] = request.env["omniauth.auth"]
          # redirect_to new_user_registration_url
        end
      end
    end

''' my routes

Rails.application.routes.draw do
  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
  resources :users
end

devise.rb

Devise.setup do |config|
  config.mailer_sender = 'DokRx@dispostable.com'

  require 'devise/orm/active_record'

  config.case_insensitive_keys = [:email]

  config.strip_whitespace_keys = [:email]

  config.skip_session_storage = [:http_auth]

  config.stretches = Rails.env.test? ? 1 : 12

  config.reconfirmable = true

  config.expire_all_remember_me_on_sign_out = true

  config.password_length = 6..128
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  config.reset_password_within = 6.hours

  config.sign_out_via = :delete

  google_client_id = Rails.application.credentials.google_oauth2[:google_client_id]
  google_client_secret = Rails.application.credentials.google_oauth2[:google_client_secret]
  config.omniauth :google_oauth2, google_client_id, google_client_secret,
    scope: 'userinfo.email, calendar',
    skip_jwt: true,
    access_type: "offline",
    prompt: "consent",
    select_account: true
    

 
end

Solution

  • 1.) check your have this version of devise to fix the "not found, Aunthentication passthru" problem :

    gem 'devise', github: 'heartcombo/devise', branch: 'ca-omniauth-2'
    

    And be sure you make a post request. For exemple :

    = link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path, method: :post
    

    https://github.com/heartcombo/devise/issues/5236

    2.) Install the following gem to fix the authenticity error :

    gem "omniauth-rails_csrf_protection"
    

    https://github.com/cookpad/omniauth-rails_csrf_protection