Oauth2 strategy for Google
Strategy to authenticate with Google via OAuth2 in OmniAuth.
Get your API key at: https://console.cloud.google.com. Note the Client ID and the Client Secret.
For more details, read the Google docs: https://developers.google.com/identity/protocols/oauth2
Add to your Gemfile:
gem 'omniauth-google-oauth2'Then bundle install.
Here's an example for adding the middleware to a Rails app in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
end
OmniAuth.config.allowed_request_methods = %i[get]You can now access the OmniAuth Google OAuth2 URL: /auth/google_oauth2
For more examples please check out examples/omni_auth.rb
Using Devise? Skip the above and jump down to the Devise section! After setting up the provider via Devise, you can reference the configurations below.
NOTE: While developing your application, if you change the scope in the initializer you will need to restart your app server. Remember that either the 'email' or 'profile' scope is required!
You can configure several options, which you pass in to the provider method via a hash:
scope: A comma-separated list of permissions you want to request from the user. See the Google OAuth 2.0 Playground for a full list of available permissions. Caveats:
email and profile scopes are used by default. By defining your own scope, you override these defaults, but Google requires at least one of email or profile, so make sure to add at least one of them to your scope!https://www.googleapis.com/auth/ do not need that prefix specified. So while you can use the smaller scope books since that permission starts with the mentioned prefix, you should use the full scope URL https://docs.google.com/feeds/ to access a user's docs, for example.redirect_uri: Override the redirect_uri used by the gem.
prompt: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are:
none: No authentication or consent pages will be displayed; it will return an error if the user is not already authenticated and has not pre-configured consent for the requested scopes. This can be used as a method to check for existing authentication and/or consent.consent: The user will always be prompted for consent, even if they have previously allowed access a given set of scopes.select_account: The user will always be prompted to select a user account. This allows a user who has multiple current account sessions to select one amongst them.If no value is specified, the user only sees the authentication page if they are not logged in and only sees the consent page the first time they authorize a given set of scopes.
image_aspect_ratio: The shape of the user's profile picture. Possible values are:
original: Picture maintains its original aspect ratio.square: Picture presents equal width and height.smart: Picture presents equal width and height with smart cropping.Defaults to original.
image_size: The size of the user's profile picture. The image returned will have width equal to the given value and variable height, according to the image_aspect_ratio chosen. Additionally, a picture with specific width and height can be requested by setting this option to a hash with width and height as keys. If only width or height is specified, a picture whose width or height is closest to the requested size and requested aspect ratio will be returned. Defaults to the original width and height of the picture.
name: The name of the strategy. The default name is google_oauth2 but it can be changed to any value, for example google. The OmniAuth URL will thus change to /auth/google and the provider key in the auth hash will then return google.
access_type: Defaults to offline, so a refresh token is sent to be used when the user is not present at the browser. Can be set to online. More about offline access
hd: (Optional) Limit sign-in to a particular Google Apps hosted domain. This can be simply string 'domain.com' or an array %w(domain.com domain.co). More information at: https://developers.google.com/accounts/docs/OpenIDConnect#hd-param
jwt_leeway: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds.
authorized_client_ids: Additional Google OAuth client IDs accepted as token audiences. The configured client_id is always accepted.
skip_jwt: Omit decoded ID token claims from extra.id_info. This only trims the auth hash; an ID token supplied by the caller in a direct access-token callback is still verified against Google's signing keys because it may be exposed as extra.id_token.
login_hint: When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fill the email box on the sign-in form, or select the proper session (if the user is using multiple sign-in), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string (the user's unique Google ID).
include_granted_scopes: If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes. See Google's Incremental Authorization for additional details.
enable_granular_consent: If this is provided with the value true, users can choose to only grant access to specific data. See Google's How to handle granular permissions guide for additional details.
openid_realm: Set the OpenID realm value, to allow upgrading from OpenID based authentication to OAuth 2 based authentication. When this is set correctly an openid_id value will be set in ['extra']['id_info'] in the authentication hash with the value of the user's OpenID ID URL.
provider_ignores_state: You will need to set this to true when using the One-time Code Flow below. In this flow there is no server side redirect that would set the state.
overridable_authorize_options: By default, all authorize_options can be overridden with request parameters. You can restrict the behavior by using this option.
Here's an example of a possible configuration where the strategy name is changed, the user is asked for extra permissions, the user is always prompted to select their account when logging in and the user's profile picture is returned as a thumbnail:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{
scope: 'email, profile, http://gdata.youtube.com',
prompt: 'select_account',
image_aspect_ratio: 'square',
image_size: 50
}
endHere's an example of an authentication hash available in the callback by accessing request.env['omniauth.auth']:
…First define your application id and secret in config/initializers/devise.rb. Do not use the snippet mentioned in the Usage section.
Configuration options can be passed as the last parameter here as key/value pairs.
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {}NOTE: If you are using this gem with devise with above snippet in config/initializers/devise.rb then do not create config/initializers/omniauth.rb which will conflict with devise configurations.
Then add the following to 'config/routes.rb' so the callback routes are defined.
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }Make sure your model is omniauthable. Generally this is "/app/models/user.rb"
devise :omniauthable, omniauth_providers: [:google_oauth2]Then make sure your callbacks controller is setup.
…and bind to or create the user
# app/models/user.rb
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data['name'],
# email: data['email'],
# password: Devise.friendly_token[0,20]
# )
# end
user
endFor your views you can login using:
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>An overview is available at https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview
If you authenticate your user from multiple different platforms with a single API you will likely have different Google client_id depending on the platform.
This could raise errors in the callback step because the client_id used in the callback needs to be the same as the one used in the sign in request.
To handle multiple client_id you can register multiple omniauth middlewares in your devise initializer with different names and different client ids. You can then register each middleware in your omniauthable model and add a new action in your OmniauthCallbacksController for each additional middleware.
# config/initializers/devise.rb
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { name: 'google_oauth2' }
# Native mobile applications don't require a `client_secret`
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID_ANDROID', { name: 'google_oauth2_android' }
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID_IOS', { name: 'google_oauth2_ios' }# app/models/user.rb
devise :omniauthable, omniauth_providers: %i[google_oauth2 google_oauth2_android google_oauth2_ios]# app/controllers/users/omniauth_callbacks_controller.rb:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
# ...
end
def google_oauth2_android
# ...
end
def google_oauth2_ios
# ...
end
endGoogle describes the One-time Code Flow here. This hybrid authentication flow has significant functional and security advantages over a pure server-side or pure client-side flow. The following steps occur in this flow:
No open issues yet, or sync has not completed.