我正在尝试通过gmail功能向我的应用程序添加登录。 我使用'omniauth'和'omniauth-google-oauth2'宝石,这是我的代码
User.rb
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,:omniauthable
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
if user
return user
else
registered_user = User.where(:email => access_token.info.email).first
if registered_user
return registered_user
else
user = User.create(name: data["name"],
provider:access_token.provider,
email: data["email"],
uid: access_token.uid ,
password: Devise.friendly_token[0,20],
)
end
end
end
devise.rb
require 'omniauth-google-oauth2'
config.omniauth :google_oauth2, "APP_ID", "APP_SECRET", { access_type: "offline", approval_prompt: "" }
用我的client_id替换了APP_ID,用我的client_secret替换了APP_SECRET
的routes.rb
devise_for :users, :controllers => { : omniauth_callbacks => "omniauth_callbacks" }
omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect @user, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
授权重定向URI
http://localhost:3000/users/auth/google_oauth2/callback
当我尝试登录时,它会给出
Started GET "/users/auth/google_oauth2/callback?state=fb1921cc2fd051c677bb0058e21e17fbaa028fce2e7eb669&code=4/g2xXVC2arLfYzWGqnswcIuwkDarfdW1ZzPSJRIcdUqw" for 127.0.0.1 at 2015-10-27 16:11:31 +0530
I, [2015-10-27T16:11:31.311428 #8223] INFO -- omniauth: (google_oauth2) Callback phase initiated.
Processing by OmniauthCallbacksController#google_oauth2 as HTML
Parameters: {"state"=>"fb1921cc2fd051c677bb0058e21e17fbaa028fce2e7eb669", "code"=>"4/g2xXVC2arLfYzWGqnswcIuwkDarfdW1ZzPSJRIcdUqw"}
Completed 401 Unauthorized in 0ms
我的代码有什么问题,提前谢谢。
答案 0 :(得分:0)
在Omniauth回拨控制器中,尝试以下代码:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect @user, :event => :authentication, bypass => true
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
我刚添加了bypass =&gt;真