Collegamento semplificato con OAuth e Accedi con Google

Panoramica

Il collegamento semplificato di Accedi con Google basato su OAuth aggiunge Accedi con Google al collegamento OAuth. In questo modo, gli utenti Google possono collegare facilmente il proprio Account Google al tuo servizio e creare un nuovo account.

Per eseguire il collegamento dell'account con OAuth e Accedi con Google, segui questi passaggi generali:

  1. Per prima cosa, chiedi all'utente di dare il consenso per accedere al suo profilo Google.
  2. Utilizza le informazioni nel profilo per verificare se l'account utente esiste.
  3. Per gli utenti esistenti, collega gli account.
  4. Se non riesci a trovare una corrispondenza per l'utente Google nel tuo sistema di autenticazione, convalida il token ID ricevuto da Google. Puoi quindi creare un utente in base alle informazioni del profilo contenute nel token ID.
Questa figura mostra i passaggi che un utente deve seguire per collegare il proprio Account Google utilizzando il flusso di collegamento semplificato. Il primo screenshot mostra come un utente può selezionare la tua app per il collegamento. Il secondo screenshot consente all'utente di verificare se ha già un account sul tuo servizio. Il terzo screenshot consente all'utente di selezionare l'Account Google a cui vuole collegarsi. Il quarto screenshot mostra la conferma del collegamento dell'Account Google all'app. Il quinto screenshot mostra un account utente collegato correttamente nell'app Google.

Figura 1. Collegamento dell'account sullo smartphone di un utente con il collegamento semplificato

Requisiti per il collegamento semplificato

Implementa il server OAuth

L'endpoint di scambio di token deve supportare gli intent check, create e get. Di seguito sono riportati i passaggi completati nel flusso di collegamento dell'account e viene indicato quando vengono chiamati i diversi intent:

  1. L'utente ha un account nel tuo sistema di autenticazione? (L'utente decide selezionando SÌ o NO)
    1. SÌ : l'utente utilizza l'indirizzo email associato al suo Account Google per accedere alla tua piattaforma? (L'utente decide selezionando SÌ o NO)
      1. SÌ : l'utente ha un account corrispondente nel tuo sistema di autenticazione? (viene chiamato check intent per conferma)
        1. SÌ : viene chiamato get intent e l'account viene collegato se getIntent restituisce un risultato positivo.
        2. NO : Crea nuovo account? (L'utente decide selezionando SÌ o NO)
          1. SÌ : viene chiamato create intent e l'account viene collegato se la chiamata create intent restituisce un risultato positivo.
          2. NO : viene attivato il flusso OAuth web, l'utente viene indirizzato al browser e gli viene offerta la possibilità di eseguire il collegamento con un'email diversa.
      2. NO : viene attivato il flusso OAuth web, l'utente viene reindirizzato al browser e gli viene offerta la possibilità di eseguire il collegamento con un'email diversa.
    2. NO : l'utente ha un account corrispondente nel tuo sistema di autenticazione? (viene chiamato check intent per conferma)
      1. SÌ : viene chiamato get intent e l'account viene collegato se getIntent restituisce un risultato positivo.
      2. NO : create intent viene chiamato e l'account viene collegato se la creazione dell'intent restituisce un risultato positivo.

Verificare la presenza di un account utente esistente (check intent)

Dopo che l'utente acconsente ad accedere al proprio profilo Google, Google invia una contenente un'asserzione firmata dell'identità dell'utente Google. La l'asserzione contiene informazioni che includono l'ID dell'Account Google dell'utente, nome e indirizzo email. L'endpoint di scambio di token configurato per il progetto gestisce la richiesta.

Se l'Account Google corrispondente è già presente nella tua autenticazione di sistema, il tuo endpoint di scambio di token risponde con account_found=true. Se L'Account Google non corrisponde a un utente esistente, il tuo endpoint di scambio di token restituisce un errore HTTP 404 - Non trovato con account_found=false.

La richiesta ha il seguente modulo:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=check&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

L'endpoint di scambio di token deve essere in grado di gestire i seguenti parametri:

Parametri endpoint token
intent Per queste richieste, il valore di questo parametro è check.
grant_type Il tipo di token che viene scambiato. Per queste richieste, ha il valore urn:ietf:params:oauth:grant-type:jwt-bearer.
assertion un token JWT (JSON Web Token) che fornisce un'asserzione firmata dei l'identità dell'utente. Il JWT contiene informazioni che includono il ID dell'Account Google, nome e indirizzo email.
client_id L'ID client che hai assegnato a Google.
client_secret Il client secret che hai assegnato a Google.

Per rispondere alle richieste di intent check, l'endpoint dello scambio di token deve eseguire i seguenti passaggi:

  • Convalida e decodifica l'asserzione JWT.
  • Verifica se l'Account Google è già presente nel sistema di autenticazione.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verified can also be true as Google initially verified the user when the Google account was created, however ownership of the third party email account may have since changed.

Controllare se l'Account Google è già presente nel sistema di autenticazione

Controlla se è vera una delle seguenti condizioni:

  • L'ID Account Google, che si trova nel campo sub dell'asserzione, è nel tuo utente per configurare un database.
  • L'indirizzo email nell'asserzione corrisponde a un utente nel tuo database utenti.

Se una delle condizioni è vera, l'utente ha già effettuato la registrazione. In questo caso, restituiscono una risposta simile alla seguente:

HTTP/1.1 200 Success
Content-Type: application/json;charset=UTF-8

{
  "account_found":"true",
}

Se né l'ID Account Google né l'indirizzo email specificato nella asserzione corrisponde a un utente presente nel tuo database, l'utente non si è ancora registrato. Nella In questo caso, l'endpoint di scambio di token deve rispondere con un errore HTTP 404. che specifica "account_found": "false", come nell'esempio seguente:

HTTP/1.1 404 Not found
Content-Type: application/json;charset=UTF-8

{
  "account_found":"false",
}

Gestire il collegamento automatico (ottenere l'intenzione)

Dopo che l'utente acconsente ad accedere al proprio profilo Google, Google invia una contenente un'asserzione firmata dell'identità dell'utente Google. La l'asserzione contiene informazioni che includono l'ID dell'Account Google dell'utente, nome e indirizzo email. L'endpoint di scambio di token configurato per il progetto gestisce la richiesta.

Se l'Account Google corrispondente è già presente nell'autenticazione il tuo endpoint di scambio di token restituisce un token per l'utente. Se L'Account Google non corrisponde a un utente esistente, il tuo endpoint di scambio di token restituisce un errore linking_error e un valore facoltativo per il campo login_hint.

La richiesta ha il seguente modulo:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=get&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

L'endpoint di scambio di token deve essere in grado di gestire i seguenti parametri:

Parametri endpoint token
intent Per queste richieste, il valore di questo parametro è get.
grant_type Il tipo di token che viene scambiato. Per queste richieste, ha il valore urn:ietf:params:oauth:grant-type:jwt-bearer.
assertion un token JWT (JSON Web Token) che fornisce un'asserzione firmata dei l'identità dell'utente. Il JWT contiene informazioni che includono il ID dell'Account Google, nome e indirizzo email.
scope Facoltativo:tutti gli ambiti che hai configurato per le richieste da parte di Google utenti.
client_id L'ID client che hai assegnato a Google.
client_secret Il client secret che hai assegnato a Google.

Per rispondere alle richieste di intent get, l'endpoint dello scambio di token deve eseguire i seguenti passaggi:

  • Convalida e decodifica l'asserzione JWT.
  • Verifica se l'Account Google è già presente nel sistema di autenticazione.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verified can also be true as Google initially verified the user when the Google account was created, however ownership of the third party email account may have since changed.

Controllare se l'Account Google è già presente nel sistema di autenticazione

Controlla se è vera una delle seguenti condizioni:

  • L'ID Account Google, che si trova nel campo sub dell'asserzione, è nel tuo utente per configurare un database.
  • L'indirizzo email nell'asserzione corrisponde a un utente nel tuo database utenti.

Se viene trovato un account per l'utente, invia un token di accesso e restituisci i valori in un oggetto JSON nel corpo della risposta HTTPS, come nell'esempio seguente:

{
  "token_type": "Bearer",
  "access_token": "ACCESS_TOKEN",
  "refresh_token": "REFRESH_TOKEN",
  "expires_in": SECONDS_TO_EXPIRATION
}

In alcuni casi, il collegamento dell'account basato sul token ID potrebbe non riuscire per l'utente. Se lo fa per qualsiasi motivo, l'endpoint di scambio di token deve rispondere con un Errore 401 che specifica error=linking_error, come mostrato nell'esempio seguente:

HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8

{
  "error":"linking_error",
  "login_hint":"foo@bar.com"
}

Quando Google riceve una risposta di errore 401 con linking_error, invia l'utente all'endpoint di autorizzazione con login_hint come parametro. La l'utente completa il collegamento dell'account utilizzando il flusso di collegamento OAuth nel proprio browser.

Handle account creation via Google Sign-In (create intent)

When a user needs to create an account on your service, Google makes a request to your token exchange endpoint that specifies intent=create.

The request has the following form:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

response_type=token&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&scope=SCOPES&intent=create&assertion=JWT&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

Your token exchange endpoint must able to handle the following parameters:

Token endpoint parameters
intent For these requests, the value of this parameter is create.
grant_type The type of token being exchanged. For these requests, this parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer.
assertion A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address.
client_id The client ID you assigned to Google.
client_secret The client secret you assigned to Google.

The JWT within the assertion parameter contains the user's Google Account ID, name, and email address, which you can use to create a new account on your service.

To respond to the create intent requests, your token exchange endpoint must perform the following steps:

  • Validate and decode the JWT assertion.
  • Validate user information and create new account.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verified can also be true as Google initially verified the user when the Google account was created, however ownership of the third party email account may have since changed.

Validate user information and create new account

Check whether either of the following conditions are true:

  • The Google Account ID, found in the assertion's sub field, is in your user database.
  • The email address in the assertion matches a user in your user database.

If either condition is true, prompt the user to link their existing account with their Google Account. To do so, respond to the request with an HTTP 401 error that specifies error=linking_error and gives the user's email address as the login_hint. The following is a sample response:

HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8

{
  "error":"linking_error",
  "login_hint":"foo@bar.com"
}

When Google receives a 401 error response with linking_error, Google sends the user to your authorization endpoint with login_hint as a parameter. The user completes account linking using the OAuth linking flow in their browser.

If neither condition is true, create a new user account with the information provided in the JWT. New accounts don't typically have a password set. It's recommended that you add Google Sign-In to other platforms to enable users to log in with Google across the surfaces of your application. Alternatively, you can email the user a link that starts your password recovery flow to allow the user to set a password to sign in on other platforms.

When the creation is completed, issue an access token and refresh token and return the values in a JSON object in the body of your HTTPS response, like in the following example:

{
  "token_type": "Bearer",
  "access_token": "ACCESS_TOKEN",
  "refresh_token": "REFRESH_TOKEN",
  "expires_in": SECONDS_TO_EXPIRATION
}

Ottenere l'ID client API di Google

Ti verrà chiesto di fornire il tuo ID client API Google durante la procedura di registrazione del collegamento dell'account.

Per ottenere l'ID client API utilizzando il progetto che hai creato durante la procedura di collegamento OAuth. Per farlo, segui questa procedura.

  1. Crea o seleziona un progetto API di Google.

    Se il progetto non ha un ID client per il tipo di applicazione web, fai clic su Crea client per crearne uno. Assicurati di includere il dominio del tuo sito nella casella Origini JavaScript autorizzate. Quando esegui sviluppi o test locali, devi aggiungere sia http://localhost che http://localhost:<port_number> al campo Origini JavaScript autorizzate.

Convalidare l'implementazione

You can validate your implementation by using the OAuth 2.0 Playground tool.

In the tool, do the following steps:

  1. Click Configuration to open the OAuth 2.0 Configuration window.
  2. In the OAuth flow field, select Client-side.
  3. In the OAuth Endpoints field, select Custom.
  4. Specify your OAuth 2.0 endpoint and the client ID you assigned to Google in the corresponding fields.
  5. In the Step 1 section, don't select any Google scopes. Instead, leave this field blank or type a scope valid for your server (or an arbitrary string if you don't use OAuth scopes). When you're done, click Authorize APIs.
  6. In the Step 2 and Step 3 sections, go through the OAuth 2.0 flow and verify that each step works as intended.

You can validate your implementation by using the Google Account Linking Demo tool.

In the tool, do the following steps:

  1. Click the Sign-in with Google button.
  2. Choose the account you'd like to link.
  3. Enter the service ID.
  4. Optionally enter one or more scopes that you will request access for.
  5. Click Start Demo.
  6. When prompted, confirm that you may consent and deny the linking request.
  7. Confirm that you are redirected to your platform.