omniauth-google-oauth2 1.2.1 → 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/Gemfile CHANGED
@@ -3,3 +3,5 @@
3
3
  source 'https://rubygems.org'
4
4
 
5
5
  gemspec
6
+
7
+ gem 'rubocop'
data/README.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  Strategy to authenticate with Google via OAuth2 in OmniAuth.
6
6
 
7
- Get your API key at: https://code.google.com/apis/console/ 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
- For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2
9
+ For more details, read the Google docs: https://developers.google.com/identity/protocols/oauth2
10
10
 
11
11
  ## Installation
12
12
 
@@ -20,10 +20,10 @@ Then `bundle install`.
20
20
 
21
21
  ## Google API Setup
22
22
 
23
- * Go to 'https://console.developers.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. Note this only works if you use jwt 2.1, as the leeway option was removed in later versions.
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, which is equivalent to the user's 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
 
@@ -121,7 +123,7 @@ Here's an example of an authentication hash available in the callback by accessi
121
123
  "last_name" => "Smith",
122
124
  "image" => "https://lh4.googleusercontent.com/photo.jpg",
123
125
  "urls" => {
124
- "google" => "https://plus.google.com/+JohnSmith"
126
+ "google" => "https://profiles.google.com/100000000000000000000"
125
127
  }
126
128
  },
127
129
  "credentials" => {
@@ -148,7 +150,7 @@ Here's an example of an authentication hash available in the callback by accessi
148
150
  "name" => "John Smith",
149
151
  "given_name" => "John",
150
152
  "family_name" => "Smith",
151
- "profile" => "https://plus.google.com/+JohnSmith",
153
+ "profile" => "https://profiles.google.com/100000000000000000000",
152
154
  "picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50",
153
155
  "email" => "john@example.com",
154
156
  "email_verified" => "true",
@@ -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.
@@ -227,64 +230,122 @@ end
227
230
  For your views you can login using:
228
231
 
229
232
  ```erb
230
- <%# omniauth-google-oauth2 1.0.x uses OmniAuth 2 and requires using HTTP Post to initiate authentication: %>
231
233
  <%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>
234
+ ```
235
+
236
+ An overview is available at https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview
237
+
238
+ #### Note about multi-platform authentication (Web, Android, IOS, ...)
239
+
240
+ If you authenticate your user from multiple different platforms with a single API you will likely have different Google `client_id` depending on the platform.
232
241
 
233
- <%# omniauth-google-oauth2 prior 1.0.0: %>
234
- <%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>
242
+ This could raise errors in the callback step because the `client_id` used in the callback needs to be the same as the one used in the sign in request.
235
243
 
236
- <%# Devise prior 4.1.0: %>
237
- <%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
244
+ To handle multiple `client_id` you can register multiple omniauth middlewares in your devise initializer with different names and different client ids. You can then register each middleware in your omniauthable model and add a new action in your `OmniauthCallbacksController` for each additional middleware.
245
+
246
+ ```ruby
247
+ # config/initializers/devise.rb
248
+
249
+ config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { name: 'google_oauth2' }
250
+
251
+ # Native mobile applications don't require a `client_secret`
252
+ config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID_ANDROID', { name: 'google_oauth2_android' }
253
+ config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID_IOS', { name: 'google_oauth2_ios' }
238
254
  ```
239
255
 
240
- An overview is available at https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview
256
+ ```ruby
257
+ # app/models/user.rb
258
+
259
+ devise :omniauthable, omniauth_providers: %i[google_oauth2 google_oauth2_android google_oauth2_ios]
260
+ ```
261
+
262
+ ```ruby
263
+ # app/controllers/users/omniauth_callbacks_controller.rb:
264
+
265
+ class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
266
+ def google_oauth2
267
+ # ...
268
+ end
269
+
270
+ def google_oauth2_android
271
+ # ...
272
+ end
273
+
274
+ def google_oauth2_ios
275
+ # ...
276
+ end
277
+ end
278
+ ```
241
279
 
242
280
  ### One-time Code Flow (Hybrid Authentication)
243
281
 
244
- 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:
282
+ Google describes the One-time Code Flow [here](https://developers.google.com/identity/protocols/oauth2). 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:
245
283
 
246
- 1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google.
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.
247
285
  2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side).
248
286
  3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback.
249
- 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.
250
288
 
251
289
  This flow is immune to replay attacks, and conveys no useful information to a man in the middle.
252
290
 
253
- 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.
254
292
 
255
293
  ```javascript
256
294
  // Basic hybrid auth example following the pattern at:
257
- // https://developers.google.com/identity/sign-in/web/reference
258
-
259
- <script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
260
-
261
- ...
262
-
263
- function init() {
264
- gapi.load('auth2', function() {
265
- // Ready.
266
- $('.google-login-button').click(function(e) {
267
- e.preventDefault();
268
-
269
- gapi.auth2.authorize({
270
- client_id: 'YOUR_CLIENT_ID',
271
- cookie_policy: 'single_host_origin',
272
- scope: 'email profile',
273
- response_type: 'code'
274
- }, function(response) {
275
- if (response && !response.error) {
276
- // google authentication succeed, now post data to server.
277
- jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response,
278
- success: function(data) {
279
- // response from server
280
- }
281
- });
282
- } else {
283
- // google authentication failed
284
- }
285
- });
286
- });
295
+ // https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow
296
+
297
+ const handleGoogleOauthSignIn = () => {
298
+ // Google's OAuth 2.0 endpoint for requesting an access token
299
+ const oauth2Endpoint = "https://accounts.google.com/o/oauth2/v2/auth";
300
+
301
+ // Parameters to pass to OAuth 2.0 endpoint.
302
+ const params = new URLSearchParams({
303
+ client_id: YOUR_CLIENT_ID,
304
+ prompt: "select_account",
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.
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.
309
+ });
310
+
311
+ const url = `${oauth2Endpoint}?${params.toString()}`;
312
+
313
+ // Create <a> element to redirect to OAuth 2.0 endpoint.
314
+ const a = document.createElement("a");
315
+ a.href = url;
316
+ a.target = "_self";
317
+
318
+ // Add a to page and click it to open the OAuth 2.0 endpoint.
319
+ document.body.appendChild(a);
320
+ a.click();
321
+ };
322
+
323
+ // Call this method when redirected to your `redirect_uri`
324
+ const handleGoogleOauthCallback = async () => {
325
+ // Get the query params Google included in your `redirect_uri`
326
+ const params = new URL(document.location.toString()).searchParams;
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.
329
+
330
+ const response = await fetch("your.api.domain/auth/google_oauth2/callback", {
331
+ body: JSON.stringify({
332
+ code,
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.
334
+ }),
335
+ headers: {
336
+ "Content-type": "application/json",
337
+ },
338
+ method: "POST",
287
339
  });
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();
288
349
  };
289
350
  ```
290
351
 
@@ -298,65 +359,25 @@ In that case, ensure to send an additional parameter `redirect_uri=` (empty stri
298
359
 
299
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.
300
361
 
301
- #### Getting around the `redirect_uri_mismatch` error (See [Issue #365](https://github.com/zquestz/omniauth-google-oauth2/issues/365))
362
+ ### Access Token Flow
302
363
 
303
- 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:
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:
304
365
 
305
- ```javascript
306
- // Initialize the GoogleAuth object
307
- let googleAuth;
308
- gapi.load('client:auth2', async () => {
309
- await gapi.client.init({ scope: '...', client_id: '...' });
310
- googleAuth = gapi.auth2.getAuthInstance();
311
- });
312
-
313
- // Call this when the Google Sign In button is clicked
314
- async function signInGoogle() {
315
- const googleUser = await googleAuth.signIn(); // wait for the user to authorize through the modal
316
- const { access_token } = googleUser.getAuthResponse();
317
-
318
- const data = new FormData();
319
- data.append('access_token', access_token);
320
-
321
- const response = await api.post('/auth/google_oauth2/callback', data)
322
- console.log(response);
323
- }
366
+ ```json
367
+ { "access_token": "ACCESS_TOKEN", "id_token": "ID_TOKEN" }
324
368
  ```
325
369
 
326
- #### Using Axios
327
- If you're making a GET resquests from another domain using `access_token`.
328
- ```
329
- axios
330
- .get(
331
- 'url(path to your callback}',
332
- { params: { access_token: 'token' } },
333
- headers....
334
- )
335
- ```
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.
336
371
 
337
- If you're making a POST resquests from another domain using `access_token`.
338
- ```
339
- axios
340
- .post(
341
- 'url(path to your callback}',
342
- { access_token: 'token' },
343
- headers....
344
- )
345
-
346
- --OR--
347
-
348
- axios
349
- .post(
350
- 'url(path to your callback}',
351
- null,
352
- {
353
- params: {
354
- access_token: 'token'
355
- },
356
- headers....
357
- }
358
- )
359
- ```
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.
360
381
 
361
382
  ## Fixing Protocol Mismatch for `redirect_uri` in Rails
362
383
 
@@ -369,7 +390,7 @@ OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http
369
390
 
370
391
  ## License
371
392
 
372
- Copyright (c) 2018 by Josh Ellithorpe
393
+ Copyright (c) 2018-2026 by Josh Ellithorpe
373
394
 
374
395
  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:
375
396
 
data/_config.yml ADDED
@@ -0,0 +1,3 @@
1
+ remote_theme: pages-themes/minimal@v0.2.0
2
+ plugins:
3
+ - jekyll-remote-theme
data/examples/Gemfile CHANGED
@@ -3,6 +3,7 @@
3
3
  source 'https://rubygems.org'
4
4
 
5
5
  gem 'omniauth-google-oauth2', path: '..'
6
+ gem 'rackup'
6
7
  gem 'rubocop'
7
8
  gem 'sinatra'
8
9
  gem 'webrick'
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,calendar'
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
@@ -38,62 +38,94 @@ class App < Sinatra::Base
38
38
  <html>
39
39
  <head>
40
40
  <title>Google OAuth2 Example</title>
41
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
41
+ </head>
42
+
43
+ <body>
44
+ <ul>
45
+ <li>
46
+ <form method="post" action="/auth/google_oauth2">
47
+ <input type="hidden" name="authenticity_token" value="#{request.env['rack.session']['csrf']}">
48
+ <button type="submit">Login with Google</button>
49
+ </form>
50
+ </li>
51
+
52
+ <li>
53
+ <a href="#" class="googleplus-login">Sign in with Google via AJAX</a>
54
+ </li>
55
+ </ul>
56
+
42
57
  <script>
43
- jQuery(function() {
44
- return $.ajax({
45
- url: 'https://apis.google.com/js/client:plus.js?onload=gpAsyncInit',
46
- dataType: 'script',
47
- cache: true
48
- });
49
- });
58
+ const a = document.querySelector('.googleplus-login');
59
+
60
+ const handleGoogleOauthSignIn = () => {
61
+ const oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
50
62
 
51
- window.gpAsyncInit = function() {
52
- gapi.auth.authorize({
53
- immediate: true,
63
+ const params = new URLSearchParams({
64
+ client_id: '#{ENV['GOOGLE_CLIENT_ID']}',
65
+ prompt: 'select_account',
66
+ redirect_uri: 'http://localhost:3000/callback',
54
67
  response_type: 'code',
55
- cookie_policy: 'single_host_origin',
56
- client_id: '#{ENV['GOOGLE_KEY']}',
57
- scope: 'email profile'
58
- }, function(response) {
59
- return;
60
- });
61
- $('.googleplus-login').click(function(e) {
62
- e.preventDefault();
63
- gapi.auth.authorize({
64
- immediate: false,
65
- response_type: 'code',
66
- cookie_policy: 'single_host_origin',
67
- client_id: '#{ENV['GOOGLE_KEY']}',
68
- scope: 'email profile'
69
- }, function(response) {
70
- if (response && !response.error) {
71
- // google authentication succeed, now post data to server.
72
- jQuery.ajax({type: 'POST', url: "/auth/google_oauth2/callback", data: response,
73
- success: function(data) {
74
- // Log the data returning from google.
75
- console.log(data)
76
- }
77
- });
78
- } else {
79
- // google authentication failed.
80
- console.log("FAILED")
81
- }
82
- });
68
+ scope: 'email openid profile',
83
69
  });
84
- };
70
+
71
+ const url = `${oauth2Endpoint}?${params.toString()}`;
72
+ window.location.href = url;
73
+ }
74
+
75
+ a.addEventListener('click', event => {
76
+ event.preventDefault();
77
+ handleGoogleOauthSignIn();
78
+ });
85
79
  </script>
80
+ </body>
81
+ </html>
82
+ HTML
83
+ end
84
+
85
+ get '/callback' do
86
+ <<-HTML
87
+ <!DOCTYPE html>
88
+ <html>
89
+ <head>
90
+ <title>Google OAuth2 Example</title>
86
91
  </head>
92
+
87
93
  <body>
88
- <ul>
89
- <li>
90
- <form method='post' action='/auth/google_oauth2'>
91
- <input type="hidden" name="authenticity_token" value="#{request.env['rack.session']['csrf']}">
92
- <button type='submit'>Login with Google</button>
93
- </form>
94
- </li>
95
- <li><a href='#' class="googleplus-login">Sign in with Google via AJAX</a></li>
96
- </ul>
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>
98
+
99
+ <script>
100
+ const handleGoogleOauthCallback = async () => {
101
+ const params = new URL(document.location.toString()).searchParams;
102
+ const code = params.get('code');
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
+ }
125
+ }
126
+
127
+ handleGoogleOauthCallback();
128
+ </script>
97
129
  </body>
98
130
  </html>
99
131
  HTML
@@ -117,13 +149,15 @@ class App < Sinatra::Base
117
149
  end
118
150
  end
119
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.
120
154
  get '/auth/failure' do
121
155
  content_type 'text/plain'
122
- begin
123
- request.env['omniauth.auth'].to_hash.inspect
124
- rescue StandardError
125
- 'No Data'
126
- end
156
+ <<~TEXT
157
+ Authentication failed
158
+ message: #{params['message'] || 'unknown'}
159
+ strategy: #{params['strategy'] || 'unknown'}
160
+ TEXT
127
161
  end
128
162
  end
129
163