We will implement google authentication with 'signet' gem. It is official ruby gem of google. It support OAuth 1.0 / OAuth 2.0 implementation.
So, in Gemfile.
gem 'signet'
run bundle.
Now, we have to create a google application on google developer console. This will provide us app_id, client_id and client_secret.
After that we will initialize the client of google auth for particular user.
In User.rb
def initialize_google_client
client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://www.googleapis.com/oauth2/v3/token',
:client_id => 'Your client Id is here',
:client_secret => 'Your client secret is here',
:scope => 'email profile',
:redirect_uri => 'redirect url same as you have put in your google application'
)
end
In above initializer you can add scope as per your requirement.
Now, we will create routes for authentication path and callback redirect path.
In routes.rb
get '/google_auth'=> 'some_controller#google_auth', as: 'google_authentication'
get 'google_callback' => 'some_controller#google_callback'
Now, in controller -
def google_auth
client = current_user.initialize_google_client
redirect_to(client.authorization_uri)
end
def google_callback
client = current_user.initialize_google_client
client.code = request['code']
token = client.fetch_access_token!
end
Above method provide you, access_token, refresh_token and id_token for particular user.
So, in Gemfile.
gem 'signet'
run bundle.
Now, we have to create a google application on google developer console. This will provide us app_id, client_id and client_secret.
After that we will initialize the client of google auth for particular user.
In User.rb
def initialize_google_client
client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://www.googleapis.com/oauth2/v3/token',
:client_id => 'Your client Id is here',
:client_secret => 'Your client secret is here',
:scope => 'email profile',
:redirect_uri => 'redirect url same as you have put in your google application'
)
end
In above initializer you can add scope as per your requirement.
Now, we will create routes for authentication path and callback redirect path.
In routes.rb
get '/google_auth'=> 'some_controller#google_auth', as: 'google_authentication'
get 'google_callback' => 'some_controller#google_callback'
Now, in controller -
def google_auth
client = current_user.initialize_google_client
redirect_to(client.authorization_uri)
end
def google_callback
client = current_user.initialize_google_client
client.code = request['code']
token = client.fetch_access_token!
end
Above method provide you, access_token, refresh_token and id_token for particular user.
So, what's next ? You give a sample for retriving a token but how to use it in Google API ? Sound easy maybe to you but it can be tricky !
ReplyDelete