omniauth-google-oauth2-1.1.1/0000755000004100000410000000000014327746124016052 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/.travis.yml0000644000004100000410000000015414327746124020163 0ustar www-datawww-datalanguage: ruby cache: bundler rvm: - '2.3.8' - '2.4.10' - '2.5.8' - '2.6.6' - '2.7.2' - '3.0.0' omniauth-google-oauth2-1.1.1/README.md0000644000004100000410000004225414327746124017340 0ustar www-datawww-data[![Gem Version](https://badge.fury.io/rb/omniauth-google-oauth2.svg)](https://badge.fury.io/rb/omniauth-google-oauth2) # OmniAuth Google OAuth2 Strategy Strategy to authenticate with Google via OAuth2 in OmniAuth. Get your API key at: https://code.google.com/apis/console/ Note the Client ID and the Client Secret. For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2 ## Installation Add to your `Gemfile`: ```ruby gem 'omniauth-google-oauth2' ``` Then `bundle install`. ## Google API Setup * Go to 'https://console.developers.google.com' * Select your project. * Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME' * Wait 10 minutes for changes to take effect. ## Usage Here's an example for adding the middleware to a Rails app in `config/initializers/omniauth.rb`: ```ruby 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` 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! ## Configuration 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](https://developers.google.com/oauthplayground/) for a full list of available permissions. Caveats: * The `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! * Scopes starting with `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. 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](https://developers.google.com/identity/protocols/OAuth2WebServer#offline) * `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. Note this only works if you use jwt 2.1, as the leeway option was removed in later versions. * `skip_jwt`: Skip JWT processing. This is for users who are seeing JWT decoding errors with the `iat` field. Always try adjusting the leeway before disabling JWT processing. * `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, which is equivalent to the user's 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](https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth) 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: ```ruby 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 } end ``` ## Auth Hash Here's an example of an authentication hash available in the callback by accessing `request.env['omniauth.auth']`: ```ruby { "provider" => "google_oauth2", "uid" => "100000000000000000000", "info" => { "name" => "John Smith", "email" => "john@example.com", "first_name" => "John", "last_name" => "Smith", "image" => "https://lh4.googleusercontent.com/photo.jpg", "urls" => { "google" => "https://plus.google.com/+JohnSmith" } }, "credentials" => { "token" => "TOKEN", "refresh_token" => "REFRESH_TOKEN", "expires_at" => 1496120719, "expires" => true }, "extra" => { "id_token" => "ID_TOKEN", "id_info" => { "azp" => "APP_ID", "aud" => "APP_ID", "sub" => "100000000000000000000", "email" => "john@example.com", "email_verified" => true, "at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q", "iss" => "accounts.google.com", "iat" => 1496117119, "exp" => 1496120719 }, "raw_info" => { "sub" => "100000000000000000000", "name" => "John Smith", "given_name" => "John", "family_name" => "Smith", "profile" => "https://plus.google.com/+JohnSmith", "picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50", "email" => "john@example.com", "email_verified" => "true", "locale" => "en", "hd" => "company.com" } } } ``` ### Devise First define your application id and secret in `config/initializers/devise.rb`. Do not use the snippet mentioned in the [Usage](https://github.com/zquestz/omniauth-google-oauth2#usage) section. Configuration options can be passed as the last parameter here as key/value pairs. ```ruby 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. ```ruby devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' } ``` Make sure your model is omniauthable. Generally this is "/app/models/user.rb" ```ruby devise :omniauthable, omniauth_providers: [:google_oauth2] ``` Then make sure your callbacks controller is setup. ```ruby # app/controllers/users/omniauth_callbacks_controller.rb: class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def google_oauth2 # You need to implement the method below in your model (e.g. app/models/user.rb) @user = User.from_omniauth(request.env['omniauth.auth']) 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'].except('extra') # Removing extra as it can overflow some session stores redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n") end end end ``` and bind to or create the user ```ruby 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 end ``` For your views you can login using: ```erb <%# omniauth-google-oauth2 1.0.x uses OmniAuth 2 and requires using HTTP Post to initiate authentication: %> <%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %> <%# omniauth-google-oauth2 prior 1.0.0: %> <%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %> <%# Devise prior 4.1.0: %> <%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %> ``` An overview is available at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview ### One-time Code Flow (Hybrid Authentication) Google describes the One-time Code Flow [here](https://developers.google.com/identity/sign-in/web/server-side-flow). 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: 1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google. 2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side). 3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback. 4. The Omniauth Google OAuth2 gem will validate the code via a server-side request to Google. If the code is valid, then Google will return an access token and, if this is the first time this user is authenticating against this application, a refresh token. Both of these should be stored on the server. The response to the AJAX request indicates the success or failure of this process. This flow is immune to replay attacks, and conveys no useful information to a man in the middle. The omniauth-google-oauth2 gem supports this mode of operation when `provider_ignores_state` is set to `true`. Implementors simply need to add the appropriate JavaScript to their web page, and they can take advantage of this flow. An example JavaScript snippet follows. ```javascript // Basic hybrid auth example following the pattern at: // https://developers.google.com/identity/sign-in/web/reference ... function init() { gapi.load('auth2', function() { // Ready. $('.google-login-button').click(function(e) { e.preventDefault(); gapi.auth2.authorize({ client_id: 'YOUR_CLIENT_ID', cookie_policy: 'single_host_origin', scope: 'email profile', response_type: 'code' }, function(response) { if (response && !response.error) { // google authentication succeed, now post data to server. jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response, success: function(data) { // response from server } }); } else { // google authentication failed } }); }); }); }; ``` #### Note about mobile clients (iOS, Android) The documentation at https://developers.google.com/identity/sign-in/ios/offline-access specifies the _REDIRECT_URI_ to be either a set value or an EMPTY string for mobile logins to work. Else, you will run into _redirect_uri_mismatch_ errors. In that case, ensure to send an additional parameter `redirect_uri=` (empty string) to the `/auth/google_oauth2/callback` URL from your mobile device. #### Note about CORS If you're making POST requests to `/auth/google_oauth2/callback` from another domain, then you need to make sure `'X-Requested-With': 'XMLHttpRequest'` header is included with your request, otherwise your server might respond with `OAuth2::Error, : Invalid Value` error. #### Getting around the `redirect_uri_mismatch` error (See [Issue #365](https://github.com/zquestz/omniauth-google-oauth2/issues/365)) If you are struggling with a persistent `redirect_uri_mismatch`, you can instead pass the `access_token` from [`getAuthResponse`](https://developers.google.com/identity/sign-in/web/reference#googleusergetauthresponseincludeauthorizationdata) directly to the `auth/google_oauth2/callback` endpoint, like so: ```javascript // Initialize the GoogleAuth object let googleAuth; gapi.load('client:auth2', async () => { await gapi.client.init({ scope: '...', client_id: '...' }); googleAuth = gapi.auth2.getAuthInstance(); }); // Call this when the Google Sign In button is clicked async function signInGoogle() { const googleUser = await googleAuth.signIn(); // wait for the user to authorize through the modal const { access_token } = googleUser.getAuthResponse(); const data = new FormData(); data.append('access_token', access_token); const response = await api.post('/auth/google_oauth2/callback', data) console.log(response); } ``` #### Using Axios If you're making a GET resquests from another domain using `access_token`. ``` axios .get( 'url(path to your callback}', { params: { access_token: 'token' } }, headers.... ) ``` If you're making a POST resquests from another domain using `access_token`. ``` axios .post( 'url(path to your callback}', { access_token: 'token' }, headers.... ) --OR-- axios .post( 'url(path to your callback}', null, { params: { access_token: 'token' }, headers.... } ) ``` ## Fixing Protocol Mismatch for `redirect_uri` in Rails Just set the `full_host` in OmniAuth based on the Rails.env. ``` # config/initializers/omniauth.rb OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http://localhost:3000' ``` ## License Copyright (c) 2018 by Josh Ellithorpe Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. omniauth-google-oauth2-1.1.1/spec/0000755000004100000410000000000014327746124017004 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/spec/omniauth/0000755000004100000410000000000014327746124020630 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/spec/omniauth/strategies/0000755000004100000410000000000014327746124023002 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/spec/omniauth/strategies/google_oauth2_spec.rb0000644000004100000410000011045714327746124027107 0ustar www-datawww-data# frozen_string_literal: true require 'spec_helper' require 'json' require 'omniauth-google-oauth2' require 'stringio' describe OmniAuth::Strategies::GoogleOauth2 do let(:request) { double('Request', params: {}, cookies: {}, env: {}) } let(:app) do lambda do [200, {}, ['Hello.']] end end subject do OmniAuth::Strategies::GoogleOauth2.new(app, 'appid', 'secret', @options || {}).tap do |strategy| allow(strategy).to receive(:request) do request end end end before do OmniAuth.config.test_mode = true end after do OmniAuth.config.test_mode = false end describe '#client_options' do it 'has correct site' do expect(subject.client.site).to eq('https://oauth2.googleapis.com') end it 'has correct authorize_url' do expect(subject.client.options[:authorize_url]).to eq('https://accounts.google.com/o/oauth2/auth') end it 'has correct token_url' do expect(subject.client.options[:token_url]).to eq('/token') end describe 'overrides' do context 'as strings' do it 'should allow overriding the site' do @options = { client_options: { 'site' => 'https://example.com' } } expect(subject.client.site).to eq('https://example.com') end it 'should allow overriding the authorize_url' do @options = { client_options: { 'authorize_url' => 'https://example.com' } } expect(subject.client.options[:authorize_url]).to eq('https://example.com') end it 'should allow overriding the token_url' do @options = { client_options: { 'token_url' => 'https://example.com' } } expect(subject.client.options[:token_url]).to eq('https://example.com') end end context 'as symbols' do it 'should allow overriding the site' do @options = { client_options: { site: 'https://example.com' } } expect(subject.client.site).to eq('https://example.com') end it 'should allow overriding the authorize_url' do @options = { client_options: { authorize_url: 'https://example.com' } } expect(subject.client.options[:authorize_url]).to eq('https://example.com') end it 'should allow overriding the token_url' do @options = { client_options: { token_url: 'https://example.com' } } expect(subject.client.options[:token_url]).to eq('https://example.com') end end end end describe '#authorize_options' do %i[access_type hd login_hint prompt scope state device_id device_name].each do |k| it "should support #{k}" do @options = { k => 'http://someval' } expect(subject.authorize_params[k.to_s]).to eq('http://someval') end end describe 'redirect_uri' do it 'should default to nil' do @options = {} expect(subject.authorize_params['redirect_uri']).to eq(nil) end it 'should set the redirect_uri parameter if present' do @options = { redirect_uri: 'https://example.com' } expect(subject.authorize_params['redirect_uri']).to eq('https://example.com') end end describe 'access_type' do it 'should default to "offline"' do @options = {} expect(subject.authorize_params['access_type']).to eq('offline') end it 'should set the access_type parameter if present' do @options = { access_type: 'online' } expect(subject.authorize_params['access_type']).to eq('online') end end describe 'hd' do it 'should default to nil' do expect(subject.authorize_params['hd']).to eq(nil) end it 'should set the hd (hosted domain) parameter if present' do @options = { hd: 'example.com' } expect(subject.authorize_params['hd']).to eq('example.com') end it 'should set the hd parameter and work with nil hd (gmail)' do @options = { hd: nil } expect(subject.authorize_params['hd']).to eq(nil) end it 'should set the hd parameter to * if set (only allows G Suite emails)' do @options = { hd: '*' } expect(subject.authorize_params['hd']).to eq('*') end end describe 'login_hint' do it 'should default to nil' do expect(subject.authorize_params['login_hint']).to eq(nil) end it 'should set the login_hint parameter if present' do @options = { login_hint: 'john@example.com' } expect(subject.authorize_params['login_hint']).to eq('john@example.com') end end describe 'prompt' do it 'should default to nil' do expect(subject.authorize_params['prompt']).to eq(nil) end it 'should set the prompt parameter if present' do @options = { prompt: 'consent select_account' } expect(subject.authorize_params['prompt']).to eq('consent select_account') end end describe 'request_visible_actions' do it 'should default to nil' do expect(subject.authorize_params['request_visible_actions']).to eq(nil) end it 'should set the request_visible_actions parameter if present' do @options = { request_visible_actions: 'something' } expect(subject.authorize_params['request_visible_actions']).to eq('something') end end describe 'include_granted_scopes' do it 'should default to nil' do expect(subject.authorize_params['include_granted_scopes']).to eq(nil) end it 'should set the include_granted_scopes parameter if present' do @options = { include_granted_scopes: 'true' } expect(subject.authorize_params['include_granted_scopes']).to eq('true') end end describe 'scope' do it 'should expand scope shortcuts' do @options = { scope: 'calendar' } expect(subject.authorize_params['scope']).to eq('https://www.googleapis.com/auth/calendar') end it 'should leave base scopes as is' do @options = { scope: 'profile' } expect(subject.authorize_params['scope']).to eq('profile') end it 'should join scopes' do @options = { scope: 'profile,email' } expect(subject.authorize_params['scope']).to eq('profile email') end it 'should deal with whitespace when joining scopes' do @options = { scope: 'profile, email' } expect(subject.authorize_params['scope']).to eq('profile email') end it 'should set default scope to email,profile' do expect(subject.authorize_params['scope']).to eq('email profile') end it 'should support space delimited scopes' do @options = { scope: 'profile email' } expect(subject.authorize_params['scope']).to eq('profile email') end it 'should support extremely badly formed scopes' do @options = { scope: 'profile email,foo,steve yeah http://example.com' } expect(subject.authorize_params['scope']).to eq('profile email https://www.googleapis.com/auth/foo https://www.googleapis.com/auth/steve https://www.googleapis.com/auth/yeah http://example.com') end end describe 'state' do it 'should set the state parameter' do @options = { state: 'some_state' } expect(subject.authorize_params['state']).to eq('some_state') expect(subject.authorize_params[:state]).to eq('some_state') expect(subject.session['omniauth.state']).to eq('some_state') end it 'should set the omniauth.state dynamically' do allow(subject).to receive(:request) { double('Request', params: { 'state' => 'some_state' }, env: {}) } expect(subject.authorize_params['state']).to eq('some_state') expect(subject.authorize_params[:state]).to eq('some_state') expect(subject.session['omniauth.state']).to eq('some_state') end end describe 'overrides' do it 'should include top-level options that are marked as :authorize_options' do @options = { authorize_options: %i[scope foo request_visible_actions], scope: 'http://bar', foo: 'baz', hd: 'wow', request_visible_actions: 'something' } expect(subject.authorize_params['scope']).to eq('http://bar') expect(subject.authorize_params['foo']).to eq('baz') expect(subject.authorize_params['hd']).to eq(nil) expect(subject.authorize_params['request_visible_actions']).to eq('something') end describe 'request overrides' do %i[access_type hd login_hint prompt scope state].each do |k| context "authorize option #{k}" do let(:request) { double('Request', params: { k.to_s => 'http://example.com' }, cookies: {}, env: {}) } context 'when overridable_authorize_options is default' do it "should set the #{k} authorize option dynamically in the request" do @options = { k: '' } expect(subject.authorize_params[k.to_s]).to eq('http://example.com') end end context 'when overridable_authorize_options is empty' do it "should not set the #{k} authorize option dynamically in the request" do @options = { k: '', overridable_authorize_options: [] } expect(subject.authorize_params[k.to_s]).not_to eq('http://example.com') end end end end describe 'custom authorize_options' do let(:request) { double('Request', params: { 'foo' => 'something' }, cookies: {}, env: {}) } context 'when overridable_authorize_options is default' do it 'should not support request overrides from custom authorize_options' do @options = { authorize_options: [:foo], foo: '' } expect(subject.authorize_params['foo']).not_to eq('something') end end context 'when overridable_authorize_options is customized' do it 'should support request overrides from custom authorize_options' do @options = { authorize_options: [:foo], overridable_authorize_options: [:foo], foo: '' } expect(subject.authorize_params['foo']).to eq('something') end end end end end end describe '#authorize_params' do it 'should include any authorize params passed in the :authorize_params option' do @options = { authorize_params: { request_visible_actions: 'something', foo: 'bar', baz: 'zip' }, hd: 'wow', bad: 'not_included' } expect(subject.authorize_params['request_visible_actions']).to eq('something') expect(subject.authorize_params['foo']).to eq('bar') expect(subject.authorize_params['baz']).to eq('zip') expect(subject.authorize_params['hd']).to eq('wow') expect(subject.authorize_params['bad']).to eq(nil) end end describe '#token_params' do it 'should include any token params passed in the :token_params option' do @options = { token_params: { foo: 'bar', baz: 'zip' } } expect(subject.token_params['foo']).to eq('bar') expect(subject.token_params['baz']).to eq('zip') end end describe '#token_options' do it 'should include top-level options that are marked as :token_options' do @options = { token_options: %i[scope foo], scope: 'bar', foo: 'baz', bad: 'not_included' } expect(subject.token_params['scope']).to eq('bar') expect(subject.token_params['foo']).to eq('baz') expect(subject.token_params['bad']).to eq(nil) end end describe '#callback_url' do let(:base_url) { 'https://example.com' } it 'has the correct default callback path' do allow(subject).to receive(:full_host) { base_url } allow(subject).to receive(:script_name) { '' } expect(subject.send(:callback_url)).to eq(base_url + '/auth/google_oauth2/callback') end it 'should set the callback path with script_name if present' do allow(subject).to receive(:full_host) { base_url } allow(subject).to receive(:script_name) { '/v1' } expect(subject.send(:callback_url)).to eq(base_url + '/v1/auth/google_oauth2/callback') end it 'should set the callback_path parameter if present' do @options = { callback_path: '/auth/foo/callback' } allow(subject).to receive(:full_host) { base_url } allow(subject).to receive(:script_name) { '' } expect(subject.send(:callback_url)).to eq(base_url + '/auth/foo/callback') end end describe '#info' do let(:client) do OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, response_hash.to_json] } end end end let(:access_token) { OAuth2::AccessToken.from_hash(client, { 'access_token' => 'a' }) } before { allow(subject).to receive(:access_token).and_return(access_token) } context 'with verified email' do let(:response_hash) do { email: 'something@domain.invalid', email_verified: true } end it 'should return equal email and unverified_email' do expect(subject.info[:email]).to eq('something@domain.invalid') expect(subject.info[:unverified_email]).to eq('something@domain.invalid') end end context 'with unverified email' do let(:response_hash) do { email: 'something@domain.invalid', email_verified: false } end it 'should return nil email, and correct unverified email' do expect(subject.info[:email]).to eq(nil) expect(subject.info[:unverified_email]).to eq('something@domain.invalid') end end end describe '#credentials' do let(:client) { OAuth2::Client.new('abc', 'def') } let(:access_token) { OAuth2::AccessToken.from_hash(client, access_token: 'valid_access_token', expires_at: 123_456_789, refresh_token: 'valid_refresh_token') } before(:each) do allow(subject).to receive(:access_token).and_return(access_token) subject.options.client_options[:connection_build] = proc do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/tokeninfo?access_token=valid_access_token') do [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump( aud: '000000000000.apps.googleusercontent.com', sub: '123456789', scope: 'profile email' )] end end end end it 'should return access token and (optionally) refresh token' do expect(subject.credentials.to_h).to \ match(hash_including( 'token' => 'valid_access_token', 'refresh_token' => 'valid_refresh_token', 'scope' => 'profile email', 'expires_at' => 123_456_789, 'expires' => true )) end end describe '#extra' do let(:client) do OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, '{"sub": "12345"}'] } end end end before { allow(subject).to receive(:access_token).and_return(access_token) } describe 'id_token' do shared_examples 'id_token issued by valid issuer' do |issuer| context 'when the id_token is passed into the access token' do let(:token_info) do { 'abc' => 'xyz', 'exp' => Time.now.to_i + 3600, 'nbf' => Time.now.to_i - 60, 'iat' => Time.now.to_i, 'aud' => 'appid', 'iss' => issuer } end let(:id_token) { JWT.encode(token_info, 'secret') } let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) } it 'should include id_token when set on the access_token' do expect(subject.extra).to include(id_token: id_token) end it 'should include id_info when id_token is set on the access_token and skip_jwt is false' do subject.options[:skip_jwt] = false expect(subject.extra).to include(id_info: token_info) end it 'should not include id_info when id_token is set on the access_token and skip_jwt is true' do subject.options[:skip_jwt] = true expect(subject.extra).not_to have_key(:id_info) end it 'should include id_info when id_token is set on the access_token by default' do expect(subject.extra).to include(id_info: token_info) end end end it_behaves_like 'id_token issued by valid issuer', 'accounts.google.com' it_behaves_like 'id_token issued by valid issuer', 'https://accounts.google.com' context 'when the id_token is issued by an invalid issuer' do let(:token_info) do { 'abc' => 'xyz', 'exp' => Time.now.to_i + 3600, 'nbf' => Time.now.to_i - 60, 'iat' => Time.now.to_i, 'aud' => 'appid', 'iss' => 'fake.google.com' } end let(:id_token) { JWT.encode(token_info, 'secret') } let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) } it 'raises JWT::InvalidIssuerError' do expect { subject.extra }.to raise_error(JWT::InvalidIssuerError) end end context 'when the access token is empty or nil' do let(:access_token) { OAuth2::AccessToken.new(client, nil, { 'refresh_token' => 'foo' }) } before { allow(subject.extra).to receive(:access_token).and_return(access_token) } it 'should not include id_token' do expect(subject.extra).not_to have_key(:id_token) end it 'should not include id_info' do expect(subject.extra).not_to have_key(:id_info) end end end describe 'raw_info' do let(:token_info) do { 'abc' => 'xyz', 'exp' => Time.now.to_i + 3600, 'nbf' => Time.now.to_i - 60, 'iat' => Time.now.to_i, 'aud' => 'appid', 'iss' => 'accounts.google.com' } end let(:id_token) { JWT.encode(token_info, 'secret') } let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) } context 'when skip_info is true' do before { subject.options[:skip_info] = true } it 'should not include raw_info' do expect(subject.extra).not_to have_key(:raw_info) end end context 'when skip_info is false' do before { subject.options[:skip_info] = false } it 'should include raw_info' do expect(subject.extra[:raw_info]).to eq('sub' => '12345') end end end end describe 'populate auth hash urls' do it 'should populate url map in auth hash if link present in raw_info' do allow(subject).to receive(:raw_info) { { 'name' => 'Foo', 'profile' => 'https://plus.google.com/123456' } } expect(subject.info[:urls][:google]).to eq('https://plus.google.com/123456') end it 'should not populate url map in auth hash if no link present in raw_info' do allow(subject).to receive(:raw_info) { { 'name' => 'Foo' } } expect(subject.info).not_to have_key(:urls) end end describe 'image options' do it 'should have no image if a picture is not present' do @options = { image_aspect_ratio: 'square' } allow(subject).to receive(:raw_info) { { 'name' => 'User Without Pic' } } expect(subject.info[:image]).to be_nil end describe 'when a picture is returned from google' do it 'should return the image with size specified in the `image_size` option' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') end it 'should return the image with size specified in the `image_size` option when sizing is in the picture' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh4.googleusercontent.com/url/s96-c/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh4.googleusercontent.com/url/s50/photo.jpg') end it 'should handle a picture with too many slashes correctly' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url//photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') end it 'should handle a picture with a size query parameter correctly' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') end it 'should handle a picture with a size query parameter and other valid query parameters correctly' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50&hello=true&life=42' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42') end it 'should handle a picture with other valid query parameters correctly' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?hello=true&life=42' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42') end it 'should return the image with width and height specified in the `image_size` option' do @options = { image_size: { width: 50, height: 40 } } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg') end it 'should return the image with width and height specified in the `image_size` option when sizing is in the picture' do @options = { image_size: { width: 50, height: 40 } } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/w100-h80-c/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg') end it 'should return square image when `image_aspect_ratio` is specified' do @options = { image_aspect_ratio: 'square' } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg') end it 'should return square image when `image_aspect_ratio` is specified and sizing is in the picture' do @options = { image_aspect_ratio: 'square' } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/c/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` is set' do @options = { image_aspect_ratio: 'square', image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` is set and sizing is in the picture' do @options = { image_aspect_ratio: 'square', image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/s90/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width' do @options = { image_aspect_ratio: 'square', image_size: { width: 50, height: 40 } } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width and sizing is in the picture' do @options = { image_aspect_ratio: 'square', image_size: { width: 50, height: 40 } } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/w100-h80/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg') end it 'should return original image if image url does not end in `photo.jpg`' do @options = { image_size: 50 } allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photograph.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photograph.jpg') end end it 'should return original image if no options are provided' do allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') end it 'should return correct image if google image url has double https' do allow(subject).to receive(:raw_info) { { 'picture' => 'https:https://lh3.googleusercontent.com/url/photo.jpg' } } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') end end describe 'build_access_token' do it 'should use a hybrid authorization request_uri if this is an AJAX request with a code parameter' do allow(request).to receive(:xhr?).and_return(true) allow(request).to receive(:params).and_return('code' => 'valid_code') client = double(:client) auth_code = double(:auth_code) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'postmessage' }, {}) expect(subject).not_to receive(:orig_build_access_token) subject.build_access_token end it 'should use a hybrid authorization request_uri if this is an AJAX request (mobile) with a code parameter' do allow(request).to receive(:xhr?).and_return(true) allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => '') client = double(:client) auth_code = double(:auth_code) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: '' }, {}) expect(subject).not_to receive(:orig_build_access_token) subject.build_access_token end it 'should use the request_uri from params if this not an AJAX request (request from installed app) with a code parameter' do allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => 'redirect_uri') client = double(:client) auth_code = double(:auth_code) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri' }, {}) expect(subject).not_to receive(:orig_build_access_token) subject.build_access_token end it 'should read access_token from hash if this is not an AJAX request with a code parameter' do client = OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, '{"sub": "12345"}'] } end end allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:params).and_return('access_token' => 'valid_access_token') expect(subject).to receive(:verify_token).with('valid_access_token').and_return true expect(subject).to receive(:client).and_return(client) token = subject.build_access_token expect(token).to be_instance_of(::OAuth2::AccessToken) expect(token.token).to eq('valid_access_token') expect(token.client).to eq(client) end it 'reads the code from a json request body' do body = StringIO.new(%({"code":"json_access_token"})) client = double(:client) auth_code = double(:auth_code) allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:content_type).and_return('application/json') allow(request).to receive(:body).and_return(body) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('json_access_token', { redirect_uri: 'postmessage' }, {}) subject.build_access_token end it 'reads the redirect uri from a json request body' do body = StringIO.new(%({"code":"json_access_token", "redirect_uri":"sample"})) client = double(:client) auth_code = double(:auth_code) allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:content_type).and_return('application/json') allow(request).to receive(:body).and_return(body) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('json_access_token', { redirect_uri: 'sample' }, {}) subject.build_access_token end it 'reads the access token from a json request body' do body = StringIO.new(%({"access_token":"valid_access_token"})) client = OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, '{"sub": "12345"}'] } end end allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:content_type).and_return('application/json') allow(request).to receive(:body).and_return(body) expect(subject).to receive(:client).and_return(client) expect(subject).to receive(:verify_token).with('valid_access_token').and_return true token = subject.build_access_token expect(token).to be_instance_of(::OAuth2::AccessToken) expect(token.token).to eq('valid_access_token') expect(token.client).to eq(client) end it 'should use callback_url without query_string if this is not an AJAX request' do allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:params).and_return('code' => 'valid_code') allow(request).to receive(:content_type).and_return('application/x-www-form-urlencoded') client = double(:client) auth_code = double(:auth_code) allow(client).to receive(:auth_code).and_return(auth_code) allow(subject).to receive(:callback_url).and_return('redirect_uri_without_query_string') expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri_without_query_string' }, {}) subject.build_access_token end end describe 'verify_token' do before(:each) do subject.options.client_options[:connection_build] = proc do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/tokeninfo?access_token=valid_access_token') do [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump( aud: '000000000000.apps.googleusercontent.com', sub: '123456789', email_verified: 'true', email: 'example@example.com', access_type: 'offline', scope: 'profile email', expires_in: 436 )] end stub.get('/oauth2/v3/tokeninfo?access_token=invalid_access_token') do [400, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(error_description: 'Invalid Value')] end end end end it 'should verify token if access_token is valid and app_id equals' do subject.options.client_id = '000000000000.apps.googleusercontent.com' expect(subject.send(:verify_token, 'valid_access_token')).to eq(true) end it 'should verify token if access_token is valid and app_id authorized' do subject.options.authorized_client_ids = ['000000000000.apps.googleusercontent.com'] expect(subject.send(:verify_token, 'valid_access_token')).to eq(true) end it 'should not verify token if access_token is valid but app_id is false' do expect(subject.send(:verify_token, 'valid_access_token')).to eq(false) end it 'should raise error if access_token is invalid' do expect do subject.send(:verify_token, 'invalid_access_token') end.to raise_error(OAuth2::Error) end end describe 'verify_hd' do let(:client) do OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') do [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump( hd: 'example.com' )] end end end end let(:access_token) { OAuth2::AccessToken.from_hash(client, { 'access_token' => 'foo' }) } context 'when domain is nil' do let(:client) do OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v3/userinfo') do [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump({})] end end end end it 'should verify hd if options hd is set and correct' do subject.options.hd = nil expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should verify hd if options hd is set as an array and is correct' do subject.options.hd = ['example.com', 'example.co', nil] expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should raise an exception if nil is not included' do subject.options.hd = ['example.com', 'example.co'] expect do subject.send(:verify_hd, access_token) end.to raise_error(OmniAuth::Strategies::OAuth2::CallbackError) end end it 'should verify hd if options hd is not set' do expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should verify hd if options hd is set and correct' do subject.options.hd = 'example.com' expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should verify hd if options hd is set as an array and is correct' do subject.options.hd = ['example.com', 'example.co', nil] expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should verify hd if options hd is set as an Proc and is correct' do subject.options.hd = proc { 'example.com' } expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should verify hd if options hd is set as an Proc returning an array and is correct' do subject.options.hd = proc { ['example.com', 'example.co'] } expect(subject.send(:verify_hd, access_token)).to eq(true) end it 'should raise error if options hd is set and wrong' do subject.options.hd = 'invalid.com' expect do subject.send(:verify_hd, access_token) end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError) end it 'should raise error if options hd is set as an array and is not correct' do subject.options.hd = ['invalid.com', 'invalid.co'] expect do subject.send(:verify_hd, access_token) end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError) end end end omniauth-google-oauth2-1.1.1/spec/spec_helper.rb0000644000004100000410000000012514327746124021620 0ustar www-datawww-data# frozen_string_literal: true require File.join('bundler', 'setup') require 'rspec' omniauth-google-oauth2-1.1.1/spec/rubocop_spec.rb0000644000004100000410000000031014327746124022006 0ustar www-datawww-data# frozen_string_literal: true require_relative 'spec_helper' describe 'Rubocop' do it 'should pass with no offenses detected' do expect(`rubocop`).to include('no offenses detected') end end omniauth-google-oauth2-1.1.1/CHANGELOG.md0000644000004100000410000001456614327746124017677 0ustar www-datawww-data# Changelog All notable changes to this project will be documented in this file. ## 1.1.1 - 2022-09-05 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Fixed JWT decoding issue. (Invalid segment encoding) [#431](https://github.com/zquestz/omniauth-google-oauth2/pull/431) ## 1.1.0 - 2022-09-03 ### Added - `overridable_authorize_options` has been added to restrict overriding authorize_options by request params. [#423](https://github.com/zquestz/omniauth-google-oauth2/pull/423) - Support for oauth2 2.0.x. [#429](https://github.com/zquestz/omniauth-google-oauth2/pull/429) ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 1.0.1 - 2022-03-10 ### Added - Output granted scopes in credentials block of the auth hash. - Migrated to GitHub actions. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Overriding the `redirect_uri` via params or JSON request body. ## 1.0.0 - 2021-03-14 ### Added - Support for Omniauth 2.x! ### Deprecated - Nothing. ### Removed - Support for Omniauth 1.x. ### Fixed - Nothing. ## 0.8.2 - 2021-03-14 ### Added - Constrains the version to Omniauth 1.x. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 0.8.1 - 2020-12-12 ### Added - Support reading the access token from a json request body. ### Deprecated - Nothing. ### Removed - No longer verify the iat claim for JWT. ### Fixed - A few minor issues with .rubocop.yml. - Issues with image resizing code when the image came with size information from Google. ## 0.8.0 - 2019-08-21 ### Added - Updated omniauth-oauth2 to v1.6.0 for security fixes. ### Deprecated - Nothing. ### Removed - Ruby 2.1 support. ### Fixed - Nothing. ## 0.7.0 - 2019-06-03 ### Added - Ensure `info[:email]` is always verified, and include `unverified_email` ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 0.6.1 - 2019-03-07 ### Added - Return `email` and `email_verified` keys in response. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 0.6.0 - 2018-12-28 ### Added - Support for JWT 2.x. ### Deprecated - Nothing. ### Removed - Support for JWT 1.x. - Support for `raw_friend_info` and `raw_image_info`. - Stop using Google+ API endpoints. ### Fixed - Nothing. ## 0.5.4 - 2018-12-07 ### Added - New recommended endpoints for Google OAuth. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 0.5.3 - 2018-01-25 ### Added - Added support for the JWT 2.x gem. - Now fully qualifies the `JWT` class to prevent conflicts with the `Omniauth::JWT` strategy. ### Deprecated - Nothing. ### Removed - Removed the `multijson` dependency. - Support for versions of `omniauth-oauth2` < 1.5. ### Fixed - Nothing. ## 0.5.2 - 2017-07-30 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - New `authorize_url` and `token_url` endpoints are reverted until JWT 2.0 ships. ### Fixed - Nothing. ## 0.5.1 - 2017-07-19 ### Added - *Breaking* JWT iss verification can be enabled/disabled with the `verify_iss` flag - see the README for more details. - Authorize options now includes `device_id` and `device_name` for private ip ranges. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Updated `authorize_url` and `token_url` to new endpoints. ## 0.5.0 - 2017-05-29 ### Added - Rubocop checks to specs. - Defaulted dev environment to ruby 2.3.4. ### Deprecated - Nothing. ### Removed - Testing support for older versions of ruby not supported by OmniAuth 1.5. - Key `[:urls]['Google']` no longer exists, it has been renamed to `[:urls][:google]`. ### Fixed - Updated all code to rubocop conventions. This includes the Ruby 1.9 hash syntax when appropriate. - Example javascript flow now picks up ENV vars for google key and secret. ## 0.4.1 - 2016-03-14 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Fixed JWT iat leeway by requiring ruby-jwt 1.5.2 ## 0.4.0 - 2016-03-11 ### Added - Addedd ability to specify multiple hosted domains. - Added a default leeway of 1 minute to JWT token validation. - Now requires ruby-jwt 1.5.x. ### Deprecated - Nothing. ### Removed - Removed support for ruby 1.9.3 as ruby-jwt 1.5.x does not support it. ### Fixed - Nothing. ## 0.3.1 - 2016-01-28 ### Added - Verify Hosted Domain if hd is set in options. ### Deprecated - Nothing. ### Removed - Dependency on addressable. ### Fixed - Nothing. ## 0.3.0 - 2016-01-09 ### Added - Updated verify_token to use the v3 tokeninfo endpoint. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Compatibility with omniauth-oauth2 1.4.0 ## 0.2.10 - 2015-11-05 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Removed some checks on the id_token. Now only parses the id_token in the JWT processing. ### Fixed - Nothing. ## 0.2.9 - 2015-10-29 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Issue with omniauth-oauth2 where redirect_uri was handled improperly. We now lock the dependency to ~> 1.3.1 ## 0.2.8 - 2015-10-01 ### Added - Added skip_jwt option to bypass JWT decoding in case you get decoding errors. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Resolved JWT::InvalidIatError. https://github.com/zquestz/omniauth-google-oauth2/issues/195 ## 0.2.7 - 2015-09-25 ### Added - Now strips out the 'sz' parameter from profile image urls. - Now uses 'addressable' gem for URI actions. - Added image data to extras hash. - Override validation on JWT token for open_id token. - Handle authorization codes coming from an installed applications. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Fixes double slashes in google image urls. ## 0.2.6 - 2014-10-26 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Hybrid authorization issues due to bad method alias. ## 0.2.5 - 2014-07-09 ### Added - Support for versions of omniauth past 1.0.x. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Nothing. ## 0.2.4 - 2014-04-25 ### Added - Now requiring the "Contacts API" and "Google+ API" to be enabled in your Google API console. ### Deprecated - The old Google OAuth API support was removed without deprecation. ### Removed - Support for the old Google OAuth API. `OAuth2::Error` will be thrown and state that access is not configured when you attempt to authenticate using the old API. See Added section for this release. ### Fixed - Nothing. omniauth-google-oauth2-1.1.1/.rubocop.yml0000644000004100000410000000066314327746124020331 0ustar www-datawww-dataMetrics/ClassLength: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: ExcludedMethods: ['describe', 'context', 'shared_examples'] Metrics/CyclomaticComplexity: Enabled: false Metrics/LineLength: Enabled: false Metrics/MethodLength: Enabled: false Metrics/PerceivedComplexity: Enabled: false Naming: Enabled: false Style/MutableConstant: Enabled: false Gemspec/RequiredRubyVersion: Enabled: false omniauth-google-oauth2-1.1.1/.gitignore0000644000004100000410000000031314327746124020037 0ustar www-datawww-data*.gem *.rbc .bundle .config .yardoc .ruby-gemset .ruby-version .rvmrc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp .powenv .idea/ omniauth-google-oauth2-1.1.1/examples/0000755000004100000410000000000014327746124017670 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/examples/config.ru0000644000004100000410000000763114327746124021514 0ustar www-datawww-data# frozen_string_literal: true # Sample app for Google OAuth2 Strategy # Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET # Run with "bundle exec rackup" require 'rubygems' require 'bundler' require 'sinatra' require 'omniauth' require 'omniauth-google-oauth2' # Do not use for production code. # This is only to make setup easier when running through the sample. # # If you do have issues with certs in production code, this could help: # http://railsapps.github.io/openssl-certificate-verify-failed.html OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE # Main example app for omniauth-google-oauth2 class App < Sinatra::Base configure do set :sessions, true set :inline_templates, true end use Rack::Session::Cookie, secret: ENV['RACK_COOKIE_SECRET'] use OmniAuth::Builder do # For additional provider examples please look at 'omni_auth.rb' # The key provider_ignores_state is only for AJAX flows. It is not recommended for normal logins. provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile,calendar' end get '/' do <<-HTML Google OAuth2 Example HTML end post '/auth/:provider/callback' do content_type 'text/plain' begin request.env['omniauth.auth'].to_hash.inspect rescue StandardError 'No Data' end end get '/auth/:provider/callback' do content_type 'text/plain' begin request.env['omniauth.auth'].to_hash.inspect rescue StandardError 'No Data' end end get '/auth/failure' do content_type 'text/plain' begin request.env['omniauth.auth'].to_hash.inspect rescue StandardError 'No Data' end end end run App.new omniauth-google-oauth2-1.1.1/examples/omni_auth.rb0000644000004100000410000000324714327746124022206 0ustar www-datawww-data# frozen_string_literal: true # Google's OAuth2 docs. Make sure you are familiar with all the options # before attempting to configure this gem. # https://developers.google.com/accounts/docs/OAuth2Login Rails.application.config.middleware.use OmniAuth::Builder do # Default usage, this will give you offline access and a refresh token # using default scopes 'email' and 'profile' # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'email,profile' # Custom redirect_uri # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'email,profile', redirect_uri: 'https://localhost:3000/redirect' # Manual setup for offline access with a refresh token. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline' # Custom scope supporting youtube. If you are customizing scopes, remember # to include the default scopes 'email' and 'profile' # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'http://gdata.youtube.com,email,profile,plus.me' # Custom scope for users only using Google for account creation/auth and do not require a refresh token. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'online', prompt: '' # To include information about people in your circles you must include the 'plus.login' scope. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_friends: false, scope: 'email,profile,plus.login' # If you need to acquire whether user picture is a default one or uploaded by user. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_image_info: false end omniauth-google-oauth2-1.1.1/examples/Gemfile0000644000004100000410000000023314327746124021161 0ustar www-datawww-data# frozen_string_literal: true source 'https://rubygems.org' gem 'omniauth-google-oauth2', '~> 1.1.1' gem 'rubocop' gem 'sinatra', '~> 1.4' gem 'webrick' omniauth-google-oauth2-1.1.1/Rakefile0000644000004100000410000000026014327746124017515 0ustar www-datawww-data# frozen_string_literal: true require File.join('bundler', 'gem_tasks') require File.join('rspec', 'core', 'rake_task') RSpec::Core::RakeTask.new(:spec) task default: :spec omniauth-google-oauth2-1.1.1/lib/0000755000004100000410000000000014327746124016620 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/lib/omniauth-google-oauth2.rb0000644000004100000410000000010014327746124023432 0ustar www-datawww-data# frozen_string_literal: true require 'omniauth/google_oauth2' omniauth-google-oauth2-1.1.1/lib/omniauth/0000755000004100000410000000000014327746124020444 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/lib/omniauth/google_oauth2/0000755000004100000410000000000014327746124023202 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/lib/omniauth/google_oauth2/version.rb0000644000004100000410000000014514327746124025214 0ustar www-datawww-data# frozen_string_literal: true module OmniAuth module GoogleOauth2 VERSION = '1.1.1' end end omniauth-google-oauth2-1.1.1/lib/omniauth/google_oauth2.rb0000644000004100000410000000011314327746124023522 0ustar www-datawww-data# frozen_string_literal: true require 'omniauth/strategies/google_oauth2' omniauth-google-oauth2-1.1.1/lib/omniauth/strategies/0000755000004100000410000000000014327746124022616 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/lib/omniauth/strategies/google_oauth2.rb0000644000004100000410000002176314327746124025712 0ustar www-datawww-data# frozen_string_literal: true require 'jwt' require 'oauth2' require 'omniauth/strategies/oauth2' require 'uri' module OmniAuth module Strategies # Main class for Google OAuth2 strategy. class GoogleOauth2 < OmniAuth::Strategies::OAuth2 ALLOWED_ISSUERS = ['accounts.google.com', 'https://accounts.google.com'].freeze BASE_SCOPE_URL = 'https://www.googleapis.com/auth/' BASE_SCOPES = %w[profile email openid].freeze DEFAULT_SCOPE = 'email,profile' USER_INFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo' IMAGE_SIZE_REGEXP = /(s\d+(-c)?)|(w\d+-h\d+(-c)?)|(w\d+(-c)?)|(h\d+(-c)?)|c/ AUTHORIZE_OPTIONS = %i[access_type hd login_hint prompt request_visible_actions scope state redirect_uri include_granted_scopes openid_realm device_id device_name] option :name, 'google_oauth2' option :skip_friends, true option :skip_image_info, true option :skip_jwt, false option :jwt_leeway, 60 option :authorize_options, AUTHORIZE_OPTIONS option :overridable_authorize_options, AUTHORIZE_OPTIONS option :authorized_client_ids, [] option :client_options, site: 'https://oauth2.googleapis.com', authorize_url: 'https://accounts.google.com/o/oauth2/auth', token_url: '/token' def authorize_params super.tap do |params| (options[:authorize_options] & options[:overridable_authorize_options]).each do |k| params[k] = request.params[k.to_s] unless [nil, ''].include?(request.params[k.to_s]) end params[:scope] = get_scope(params) params[:access_type] = 'offline' if params[:access_type].nil? params['openid.realm'] = params.delete(:openid_realm) unless params[:openid_realm].nil? session['omniauth.state'] = params[:state] if params[:state] end end uid { raw_info['sub'] } info do prune!( name: raw_info['name'], email: verified_email, unverified_email: raw_info['email'], email_verified: raw_info['email_verified'], first_name: raw_info['given_name'], last_name: raw_info['family_name'], image: image_url, urls: { google: raw_info['profile'] } ) end credentials do # Tokens and expiration will be used from OAuth2 strategy credentials block prune!({ 'scope' => token_info(access_token.token)['scope'] }) end extra do hash = {} token = nil_or_empty?(access_token['id_token']) ? access_token.token : access_token['id_token'] hash[:id_token] = token if !options[:skip_jwt] && !nil_or_empty?(token) decoded = ::JWT.decode(token, nil, false).first # We have to manually verify the claims because the third parameter to # JWT.decode is false since no verification key is provided. ::JWT::Verify.verify_claims(decoded, verify_iss: true, iss: ALLOWED_ISSUERS, verify_aud: true, aud: options.client_id, verify_sub: false, verify_expiration: true, verify_not_before: true, verify_iat: false, verify_jti: false, leeway: options[:jwt_leeway]) hash[:id_info] = decoded end hash[:raw_info] = raw_info unless skip_info? prune! hash end def raw_info @raw_info ||= access_token.get(USER_INFO_URL).parsed end def custom_build_access_token access_token = get_access_token(request) verify_hd(access_token) access_token end alias build_access_token custom_build_access_token private def nil_or_empty?(obj) obj.is_a?(String) ? obj.empty? : obj.nil? end def callback_url options[:redirect_uri] || (full_host + callback_path) end def get_access_token(request) verifier = request.params['code'] redirect_uri = request.params['redirect_uri'] access_token = request.params['access_token'] if verifier && request.xhr? client_get_token(verifier, redirect_uri || 'postmessage') elsif verifier client_get_token(verifier, redirect_uri || callback_url) elsif access_token && verify_token(access_token) ::OAuth2::AccessToken.from_hash(client, request.params.dup) elsif request.content_type =~ /json/i begin body = JSON.parse(request.body.read) request.body.rewind # rewind request body for downstream middlewares verifier = body && body['code'] access_token = body && body['access_token'] redirect_uri ||= body && body['redirect_uri'] if verifier client_get_token(verifier, redirect_uri || 'postmessage') elsif verify_token(access_token) ::OAuth2::AccessToken.from_hash(client, body.dup) end rescue JSON::ParserError => e warn "[omniauth google-oauth2] JSON parse error=#{e}" end end end def client_get_token(verifier, redirect_uri) client.auth_code.get_token(verifier, get_token_options(redirect_uri), get_token_params) end def get_token_params deep_symbolize(options.auth_token_params || {}) end def get_scope(params) raw_scope = params[:scope] || DEFAULT_SCOPE scope_list = raw_scope.split(' ').map { |item| item.split(',') }.flatten scope_list.map! { |s| s =~ %r{^https?://} || BASE_SCOPES.include?(s) ? s : "#{BASE_SCOPE_URL}#{s}" } scope_list.join(' ') end def verified_email raw_info['email_verified'] ? raw_info['email'] : nil end def get_token_options(redirect_uri = '') { redirect_uri: redirect_uri }.merge(token_params.to_hash(symbolize_keys: true)) end def prune!(hash) hash.delete_if do |_, v| prune!(v) if v.is_a?(Hash) v.nil? || (v.respond_to?(:empty?) && v.empty?) end end def image_url return nil unless raw_info['picture'] u = URI.parse(raw_info['picture'].gsub('https:https', 'https')) path_index = u.path.to_s.index('/photo.jpg') if path_index && image_size_opts_passed? u.path.insert(path_index, image_params) u.path = u.path.gsub('//', '/') # Check if the image is already sized! split_path = u.path.split('/') u.path = u.path.sub("/#{split_path[-3]}", '') if split_path[-3] =~ IMAGE_SIZE_REGEXP end u.query = strip_unnecessary_query_parameters(u.query) u.to_s end def image_size_opts_passed? options[:image_size] || options[:image_aspect_ratio] end def image_params image_params = [] if options[:image_size].is_a?(Integer) image_params << "s#{options[:image_size]}" elsif options[:image_size].is_a?(Hash) image_params << "w#{options[:image_size][:width]}" if options[:image_size][:width] image_params << "h#{options[:image_size][:height]}" if options[:image_size][:height] end image_params << 'c' if options[:image_aspect_ratio] == 'square' '/' + image_params.join('-') end def strip_unnecessary_query_parameters(query_parameters) # strip `sz` parameter (defaults to sz=50) which overrides `image_size` options return nil if query_parameters.nil? params = CGI.parse(query_parameters) stripped_params = params.delete_if { |key| key == 'sz' } # don't return an empty Hash since that would result # in URLs with a trailing ? character: http://image.url? return nil if stripped_params.empty? URI.encode_www_form(stripped_params) end def token_info(access_token) return nil unless access_token @token_info ||= Hash.new do |h, k| h[k] = client.request(:get, 'https://www.googleapis.com/oauth2/v3/tokeninfo', params: { access_token: access_token }).parsed end @token_info[access_token] end def verify_token(access_token) return false unless access_token token_info = token_info(access_token) token_info['aud'] == options.client_id || options.authorized_client_ids.include?(token_info['aud']) end def verify_hd(access_token) return true unless options.hd @raw_info ||= access_token.get(USER_INFO_URL).parsed options.hd = options.hd.call if options.hd.is_a? Proc allowed_hosted_domains = Array(options.hd) raise CallbackError.new(:invalid_hd, 'Invalid Hosted Domain') unless allowed_hosted_domains.include?(@raw_info['hd']) || options.hd == '*' true end end end end omniauth-google-oauth2-1.1.1/Gemfile0000644000004100000410000000010614327746124017342 0ustar www-datawww-data# frozen_string_literal: true source 'https://rubygems.org' gemspec omniauth-google-oauth2-1.1.1/.github/0000755000004100000410000000000014327746124017412 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/.github/workflows/0000755000004100000410000000000014327746124021447 5ustar www-datawww-dataomniauth-google-oauth2-1.1.1/.github/workflows/ci.yml0000644000004100000410000000074314327746124022571 0ustar www-datawww-dataname: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: ruby-version: ['2.3', '2.4', '2.5', '2.6', '2.7', '3.0', '3.1'] steps: - uses: actions/checkout@v2 - name: Set up Ruby ${{ matrix.ruby-version }} uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # 'bundle install' and cache - name: Run specs run: | bundle exec rake omniauth-google-oauth2-1.1.1/omniauth-google-oauth2.gemspec0000644000004100000410000000217214327746124023717 0ustar www-datawww-data# frozen_string_literal: true require File.expand_path( File.join('..', 'lib', 'omniauth', 'google_oauth2', 'version'), __FILE__ ) Gem::Specification.new do |gem| gem.name = 'omniauth-google-oauth2' gem.version = OmniAuth::GoogleOauth2::VERSION gem.license = 'MIT' gem.summary = %(A Google OAuth2 strategy for OmniAuth 1.x) gem.description = %(A Google OAuth2 strategy for OmniAuth 1.x. This allows you to login to Google with your ruby app.) gem.authors = ['Josh Ellithorpe', 'Yury Korolev'] gem.email = ['quest@mac.com'] gem.homepage = 'https://github.com/zquestz/omniauth-google-oauth2' gem.files = `git ls-files`.split("\n") gem.require_paths = ['lib'] gem.required_ruby_version = '>= 2.2' gem.add_runtime_dependency 'jwt', '>= 2.0' gem.add_runtime_dependency 'oauth2', '~> 2.0.6' gem.add_runtime_dependency 'omniauth', '~> 2.0' gem.add_runtime_dependency 'omniauth-oauth2', '~> 1.8.0' gem.add_development_dependency 'rake', '~> 12.0' gem.add_development_dependency 'rspec', '~> 3.6' gem.add_development_dependency 'rubocop', '~> 0.49' end