omniauth-google-oauth2 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  Strategy to authenticate with Google via OAuth2 in OmniAuth.
6
6
 
7
- Get your API key at: https://console.cloud.google.com Note the Client ID and the Client Secret.
7
+ Get your API key at: https://console.cloud.google.com. Note the Client ID and the Client Secret.
8
8
 
9
9
  For more details, read the Google docs: https://developers.google.com/identity/protocols/oauth2
10
10
 
@@ -20,10 +20,10 @@ Then `bundle install`.
20
20
 
21
21
  ## Google API Setup
22
22
 
23
- * Go to 'https://console.cloud.google.com'
24
- * Select your project.
25
- * Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME'
26
- * Wait 10 minutes for changes to take effect.
23
+ - Go to 'https://console.cloud.google.com'
24
+ - Select your project.
25
+ - Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME'
26
+ - Wait 10 minutes for changes to take effect.
27
27
 
28
28
  ## Usage
29
29
 
@@ -48,49 +48,51 @@ NOTE: While developing your application, if you change the scope in the initiali
48
48
 
49
49
  You can configure several options, which you pass in to the `provider` method via a hash:
50
50
 
51
- * `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:
52
- * 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!
53
- * 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.
51
+ - `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:
52
+ - 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!
53
+ - 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.
54
54
 
55
- * `redirect_uri`: Override the redirect_uri used by the gem.
55
+ - `redirect_uri`: Override the redirect_uri used by the gem.
56
56
 
57
- * `prompt`: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are:
58
- * `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.
59
- * `consent`: The user will always be prompted for consent, even if they have previously allowed access a given set of scopes.
60
- * `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.
57
+ - `prompt`: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are:
58
+ - `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.
59
+ - `consent`: The user will always be prompted for consent, even if they have previously allowed access a given set of scopes.
60
+ - `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.
61
61
 
62
62
  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.
63
63
 
64
- * `image_aspect_ratio`: The shape of the user's profile picture. Possible values are:
65
- * `original`: Picture maintains its original aspect ratio.
66
- * `square`: Picture presents equal width and height.
67
- * `smart`: Picture presents equal width and height with smart cropping.
64
+ - `image_aspect_ratio`: The shape of the user's profile picture. Possible values are:
65
+ - `original`: Picture maintains its original aspect ratio.
66
+ - `square`: Picture presents equal width and height.
67
+ - `smart`: Picture presents equal width and height with smart cropping.
68
68
 
69
69
  Defaults to `original`.
70
70
 
71
- * `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.
71
+ - `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.
72
72
 
73
- * `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`.
73
+ - `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`.
74
74
 
75
- * `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)
75
+ - `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)
76
76
 
77
- * `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
77
+ - `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
78
78
 
79
- * `jwt_leeway`: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds.
79
+ - `jwt_leeway`: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds.
80
80
 
81
- * `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.
81
+ - `authorized_client_ids`: Additional Google OAuth client IDs accepted as token audiences. The configured `client_id` is always accepted.
82
82
 
83
- * `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).
83
+ - `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`.
84
84
 
85
- * `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.
85
+ - `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).
86
86
 
87
- * `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](https://developers.google.com/identity/protocols/oauth2/resources/granular-permissions) guide for additional details.
87
+ - `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.
88
88
 
89
- * `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.
89
+ - `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](https://developers.google.com/identity/protocols/oauth2/resources/granular-permissions) guide for additional details.
90
90
 
91
- * `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.
91
+ - `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.
92
92
 
93
- * `overridable_authorize_options`: By default, all `authorize_options` can be overridden with request parameters. You can restrict the behavior by using this option.
93
+ - `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.
94
+
95
+ - `overridable_authorize_options`: By default, all `authorize_options` can be overridden with request parameters. You can restrict the behavior by using this option.
94
96
 
95
97
  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:
96
98
 
@@ -168,6 +170,7 @@ Configuration options can be passed as the last parameter here as key/value pair
168
170
  ```ruby
169
171
  config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {}
170
172
  ```
173
+
171
174
  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.
172
175
 
173
176
  Then add the following to 'config/routes.rb' so the callback routes are defined.
@@ -281,11 +284,11 @@ Google describes the One-time Code Flow [here](https://developers.google.com/ide
281
284
  1. The client (web browser) authenticates the user directly via Google's OAuth 2 API. During this process assorted modals may be rendered by Google.
282
285
  2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side).
283
286
  3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback.
284
- 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.
287
+ 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.
285
288
 
286
289
  This flow is immune to replay attacks, and conveys no useful information to a man in the middle.
287
290
 
288
- 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.
291
+ 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.
289
292
 
290
293
  ```javascript
291
294
  // Basic hybrid auth example following the pattern at:
@@ -293,48 +296,57 @@ The omniauth-google-oauth2 gem supports this mode of operation when `provider_ig
293
296
 
294
297
  const handleGoogleOauthSignIn = () => {
295
298
  // Google's OAuth 2.0 endpoint for requesting an access token
296
- const oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
299
+ const oauth2Endpoint = "https://accounts.google.com/o/oauth2/v2/auth";
297
300
 
298
301
  // Parameters to pass to OAuth 2.0 endpoint.
299
302
  const params = new URLSearchParams({
300
303
  client_id: YOUR_CLIENT_ID,
301
- prompt: 'select_account',
304
+ prompt: "select_account",
302
305
  redirect_uri: YOUR_REDIRECT_URI, // This redirect_uri needs to redirect to the same domain as the one where this request is made from.
303
- response_type: 'code',
304
- scope: 'email openid profile',
305
- state: 'google', // The state will be added in the redirect_uri's query params. Use can this if you use the same redirect_uri with different omniauth provider to know which one you're currently handling for example.
306
+ response_type: "code",
307
+ scope: "email openid profile",
308
+ state: "google", // The state will be added in the redirect_uri's query params. Use can this if you use the same redirect_uri with different omniauth provider to know which one you're currently handling for example.
306
309
  });
307
310
 
308
311
  const url = `${oauth2Endpoint}?${params.toString()}`;
309
312
 
310
313
  // Create <a> element to redirect to OAuth 2.0 endpoint.
311
- const a = document.createElement('a');
314
+ const a = document.createElement("a");
312
315
  a.href = url;
313
- a.target = '_self';
316
+ a.target = "_self";
314
317
 
315
318
  // Add a to page and click it to open the OAuth 2.0 endpoint.
316
319
  document.body.appendChild(a);
317
320
  a.click();
318
- }
321
+ };
319
322
 
320
323
  // Call this method when redirected to your `redirect_uri`
321
324
  const handleGoogleOauthCallback = async () => {
322
325
  // Get the query params Google included in your `redirect_uri`
323
326
  const params = new URL(document.location.toString()).searchParams;
324
- const code = params.get('code');
325
- const state = params.get('state') // the `state` you added in the sign in request is here if you need it.
327
+ const code = params.get("code");
328
+ const state = params.get("state"); // the `state` you added in the sign in request is here if you need it.
326
329
 
327
- const response = fetch('your.api.domain/auth/google_oauth2/callback', {
330
+ const response = await fetch("your.api.domain/auth/google_oauth2/callback", {
328
331
  body: JSON.stringify({
329
332
  code,
330
333
  redirect_uri: YOUR_REDIRECT_URI, // The `redirect_uri` used in the server needs to be the same as as initially used in the client.
331
334
  }),
332
335
  headers: {
333
- 'Content-type': 'application/json',
336
+ "Content-type": "application/json",
334
337
  },
335
- method: 'POST',
338
+ method: "POST",
336
339
  });
337
- }
340
+
341
+ // The response body is your application's own callback output, so handle it
342
+ // however suits you. A failed sign in redirects to /auth/failure, whose
343
+ // `message` query parameter says why.
344
+ if (!response.ok) {
345
+ throw new Error(`Callback failed: ${response.status}`);
346
+ }
347
+
348
+ return response.text();
349
+ };
338
350
  ```
339
351
 
340
352
  #### Note about mobile clients (iOS, Android)
@@ -347,6 +359,26 @@ In that case, ensure to send an additional parameter `redirect_uri=` (empty stri
347
359
 
348
360
  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.
349
361
 
362
+ ### Access Token Flow
363
+
364
+ As an alternative to posting a one-time code, a client that already holds a Google access token can post that instead, as either a form parameter or a JSON body:
365
+
366
+ ```json
367
+ { "access_token": "ACCESS_TOKEN", "id_token": "ID_TOKEN" }
368
+ ```
369
+
370
+ Prefer the One-time Code Flow above where you can. It is immune to replay attacks, and it lets the server obtain a refresh token. This flow exists for clients such as native mobile apps that have already completed sign-in through a Google SDK and hold tokens directly.
371
+
372
+ `access_token` is required. The gem validates it with Google before using it, and rejects it unless its audience is your own `client_id` or one of `authorized_client_ids`. `uid` and the `info` section are then read from Google's userinfo endpoint using that token, so they always describe the account the access token really belongs to.
373
+
374
+ `id_token` is optional. When present it is verified against Google's published signing keys, and its issuer, validity window, and audience are checked. Its audience must be your own `client_id` or one of `authorized_client_ids`. It must also describe the same user as the access token, established either through its `at_hash` claim or by matching the userinfo subject. Only then does it populate `extra.id_token`, and `extra.id_info` unless `skip_jwt` is set.
375
+
376
+ An ID token that fails any of those checks is discarded and the sign-in continues without it, so `extra.id_info` may be absent even though authentication succeeded. An ID token kept from an earlier sign-in will usually have expired by then, so send the one Google issued alongside the access token you are posting.
377
+
378
+ Other credential fields in the request are ignored. In particular a `refresh_token` or an expiry sent by the client is dropped rather than trusted, since neither can be verified, so `credentials.refresh_token` and `credentials.expires_at` are not populated in this flow.
379
+
380
+ A request that carries no usable credential, such as an `id_token` with no `access_token`, fails with OmniAuth's standard `invalid_credentials` failure.
381
+
350
382
  ## Fixing Protocol Mismatch for `redirect_uri` in Rails
351
383
 
352
384
  Just set the `full_host` in OmniAuth based on the Rails.env.
data/examples/config.ru CHANGED
@@ -1,7 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  # Sample app for Google OAuth2 Strategy
4
- # Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET
4
+ # Make sure to setup the ENV variables GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
5
+ # and RACK_COOKIE_SECRET
5
6
  # Run with "bundle exec rackup"
6
7
 
7
8
  require 'rubygems'
@@ -10,12 +11,11 @@ require 'sinatra'
10
11
  require 'omniauth'
11
12
  require 'omniauth-google-oauth2'
12
13
 
13
- # Do not use for production code.
14
- # This is only to make setup easier when running through the sample.
15
- #
16
- # If you do have issues with certs in production code, this could help:
17
- # http://railsapps.github.io/openssl-certificate-verify-failed.html
18
- OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
14
+ # OmniAuth re-raises authentication failures in development by default, and
15
+ # `rackup` runs in development, so the sample would show a stack trace where a
16
+ # deployed app redirects to /auth/failure. Clearing this lets the example
17
+ # demonstrate the failure a real application would see.
18
+ OmniAuth.config.failure_raise_out_environments = []
19
19
 
20
20
  # Main example app for omniauth-google-oauth2
21
21
  class App < Sinatra::Base
@@ -29,7 +29,7 @@ class App < Sinatra::Base
29
29
  use OmniAuth::Builder do
30
30
  # For additional provider examples please look at 'omni_auth.rb'
31
31
  # The key provider_ignores_state is only for AJAX flows. It is not recommended for normal logins.
32
- provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile'
32
+ provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile'
33
33
  end
34
34
 
35
35
  get '/' do
@@ -61,7 +61,7 @@ class App < Sinatra::Base
61
61
  const oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
62
62
 
63
63
  const params = new URLSearchParams({
64
- client_id: '#{ENV['GOOGLE_KEY']}',
64
+ client_id: '#{ENV['GOOGLE_CLIENT_ID']}',
65
65
  prompt: 'select_account',
66
66
  redirect_uri: 'http://localhost:3000/callback',
67
67
  response_type: 'code',
@@ -91,20 +91,37 @@ class App < Sinatra::Base
91
91
  </head>
92
92
 
93
93
  <body>
94
- <p>Redirected</p>
94
+ <h1>Google OAuth2 Example</h1>
95
+ <p>Posting the one-time code to the callback. The auth hash appears below.</p>
96
+ <p id="status">Working...</p>
97
+ <code id="result" style="white-space: pre-wrap; overflow-wrap: anywhere; display: block;"></code>
95
98
 
96
99
  <script>
97
100
  const handleGoogleOauthCallback = async () => {
98
101
  const params = new URL(document.location.toString()).searchParams;
99
102
  const code = params.get('code');
100
-
101
- const response = fetch('http://localhost:3000/auth/google_oauth2/callback', {
102
- body: JSON.stringify({ code, redirect_uri: 'http://localhost:3000/callback' }),
103
- headers: {
104
- 'Content-type': 'application/json',
105
- },
106
- method: 'POST',
107
- });
103
+ const status = document.querySelector('#status');
104
+ const output = document.querySelector('#result');
105
+
106
+ if (!code) {
107
+ status.textContent = 'No code parameter in the URL.';
108
+ return;
109
+ }
110
+
111
+ try {
112
+ const response = await fetch('http://localhost:3000/auth/google_oauth2/callback', {
113
+ body: JSON.stringify({ code, redirect_uri: 'http://localhost:3000/callback' }),
114
+ headers: {
115
+ 'Content-type': 'application/json',
116
+ },
117
+ method: 'POST',
118
+ });
119
+
120
+ status.textContent = `${response.status} ${response.statusText}`;
121
+ output.textContent = await response.text();
122
+ } catch (error) {
123
+ status.textContent = `Request failed: ${error}`;
124
+ }
108
125
  }
109
126
 
110
127
  handleGoogleOauthCallback();
@@ -132,13 +149,15 @@ class App < Sinatra::Base
132
149
  end
133
150
  end
134
151
 
152
+ # omniauth.auth is never set on a failure, so report what OmniAuth does pass:
153
+ # the failure reason and the strategy that produced it.
135
154
  get '/auth/failure' do
136
155
  content_type 'text/plain'
137
- begin
138
- request.env['omniauth.auth'].to_hash.inspect
139
- rescue StandardError
140
- 'No Data'
141
- end
156
+ <<~TEXT
157
+ Authentication failed
158
+ message: #{params['message'] || 'unknown'}
159
+ strategy: #{params['strategy'] || 'unknown'}
160
+ TEXT
142
161
  end
143
162
  end
144
163
 
@@ -2,6 +2,6 @@
2
2
 
3
3
  module OmniAuth
4
4
  module GoogleOauth2
5
- VERSION = '1.2.2'
5
+ VERSION = '1.2.3'
6
6
  end
7
7
  end