I am trying to add login through gmail feature to my application. I used 'omniauth' and 'omniauth-google-oauth2' gems,Here is my code
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: "" }
replaced APP_ID with my client_id and APP_SECRET with my client_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
authorised redirect URI
http://localhost:3000/users/auth/google_oauth2/callback
When I try to login it gives
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
Is there anything wrong in my code,Thanks in advance.
In Omniauth Call Back Controller , try the below code:
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
I just added bypass => true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.