无法使用Ruby on Rails,Devise,Omniauth在Google和玩具网站之间设置简单的OAuth2



我正在尝试通过构建一个小型web应用程序来学习Ruby on Rails。我的第一步是从OAuth登录开始,这样用户就可以使用Facebook, Google等登录。但是当我在本地主机上进入/users/sign_up设计页面并点击Sign in with GoogleOauth2时,它"什么也没做"。控制台告诉我:

D, [2021-10-05T04:55:04.716439 #10144] DEBUG -- omniauth: (google_oauth2) Request phase initiated.
W, [2021-10-05T04:55:04.730086 #10144]  WARN -- omniauth: Attack prevented by OmniAuth::AuthenticityTokenProtection
E, [2021-10-05T04:55:04.730681 #10144] ERROR -- omniauth: (google_oauth2) Authentication failure! authenticity_error: OmniAuth::AuthenticityError, Forbidden

我已经设置了设计和omniauth-google-oauth2,并在Google开发者控制台注册了一个应用程序,添加了适当的回调uri作为http://127.0.0.1:3000/users/auth/google_oauth2/callbackhttp://localhost:3000/users/auth/google_oauth2/callback,并使用dotenv gem将密钥和秘密写入.env以读取它们,使用dotenv rails server运行服务器。

我想了解这里出了什么问题,为什么,我该如何去调试这个,以及如何修复它,以便通过谷歌登录带我到我的主页,"耶!你在轨道上!屏幕。

我的文件设置如下:

routes.rb:

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

应用程序/模型/users.rb:

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise  :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:timeoutable,
:omniauthable, omniauth_providers: [:google_oauth2]
def self.create_from_google_data(provider_data)
where(provider: provider_data.provider, uid: provider_data.uid).first_or_create do | user |
user.email = provider_data.info.email
user.password = Devise.friendly_token[0, 20]
user.skip_confirmation!
end
end
end

app/config/初始化/devise.rb:

...
config.omniauth :google_oauth2, ENV['GOOGLE_APP_ID'], ENV['GOOGLE_APP_SECRET'], scope: 'userinfo.email,userinfo.profile'
...

app/controllers/用户/omniauth_controller.rb

class Users::OmniauthController < ApplicationController
def google_oauth2
@user = User.create_from_google_data(request.env['omniauth.auth'])
if @user.persisted?
sign_in_and_redirect @user
set_flash_message(:notice, :success, kind: 'Google') if is_navigational_format?
else
flash[:error] = 'There was a problem signing you in through Google. Please register or try signing in later.'
redirect_to new_user_registration_url
end 
end
def failure
flash[:error] = 'There was a problem signing you in. Please register or try signing in later.' 
redirect_to new_user_registration_url
end
end

app/config/初始化/session_store.rb:

Rails.application.config.session_store :active_record_store, key: '_devise-omniauth_session'

如果需要进一步的澄清来调试这个问题,请告诉我。

对于任何遇到同样问题的人,我通过在项目中添加以下gem来解决它,在尝试了大量的修复后,我在网上找到了:gem "omniauth-rails_csrf_protection"为什么?不清楚。

最新更新