我在将我的rails应用程序和所有宝石更新到最新版本后开始出现此错误,并且无法找出导致它的原因:
ERROR -- omniauth: (google_oauth2) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
首先是devise.rb中的初始化程序:
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{ access_type: 'offline',
prompt: 'consent',
select_account: true,
scope: 'userinfo.email,userinfo.profile',
client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}
}
User.rb有:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:google_oauth2, :facebook]
def self.from_omniauth(auth)
identity = Identity.find_for_oauth(auth)
if identity.nil?
identity = Identity.create_with_oauth(auth)
end
if identity.user.present?
return identity.user
else
registered_user = User.find_or_create_by(email: auth[:info][:email])
if registered_user && auth[:provider] == "google_oauth2"
registered_user.firstname = auth[:info][:first_name] if registered_user.firstname.blank?
registered_user.lastname = auth[:info][:last_name] if registered_user.lastname.blank?
registered_user.displayname = auth[:info][:name] if registered_user.displayname.blank?
registered_user.avatar_remote_url = auth[:info][:image] if registered_user.avatar_data.blank?
identity.user = registered_user
identity.save
registered_user.skip_confirmation!
registered_user.avatar_remote_url = auth[:info][:image]
registered_user.save
return registered_user
end
end
end
回调控制器
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# You should configure your model like this:
# devise :omniauthable, omniauth_providers: [:twitter]
# You should also create an action method in this controller like this:
def google_oauth2
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user
sign_in @user
redirect_to root_path
else
redirect_to new_user_session_path, notice: 'Access Denied.'
end
end
我已经尝试过寻找答案,但没有什么适合并且有效