Verificare il token ID di Google sul lato server

Quando utilizzi i servizi di identità Google o il flusso del codice di autorizzazione OAuth 2.0, Google restituisce il token ID utilizzando il metodo POST all'endpoint di reindirizzamento. In alternativa, il flusso implicito OIDC utilizza una richiesta GET. Di conseguenza, la tua applicazione è responsabile della trasmissione sicura di queste credenziali ricevute al tuo server.

GET

Questo è il flusso implicito, il token ID viene restituito all'interno del frammento dell'URL, che il codice JavaScript lato client deve analizzare. La tua applicazione è responsabile dell'implementazione dei propri meccanismi di convalida per garantire l'autenticità della richiesta e prevenire attacchi come CSRF.

    HTTP/1.1 302 Found
    Location: https://<REDIRECT_URI>#access_token=<ACCESS_TOKEN>&token_type=bearer&expires_in=<TIME_IN_SECONDS>&scope=<SCOPE>&state=<STATE_STRING>
    
POST

Il token ID viene restituito come campo credential. Quando si prepara a inviare il token ID al server, la libreria GIS aggiunge automaticamente g_csrf_token al cookie di intestazione e al corpo della richiesta. Ecco una richiesta POST di esempio:

POST /auth/token-verification HTTP/1.1
Host: example.com
Content-Type: application/json;charset=UTF-8
Cookie: g_csrf_token=<CSRF_TOKEN>
Origin: https://example.com
Content-Length: <LENGTH_OF_JSON_BODY>
    {
      "credential": "<ID_TOKEN>",
      "g_csrf_token": "<CSRF_TOKEN>",
      "client_id": "<CLIENT_ID>"
    }

  1. Convalida di g_csrf_token per impedire attacchi di tipo Cross-Site Request Forgery (CSRF):

    • Estrai il valore del token CSRF dal cookie g_csrf_token.
    • Estrai il valore del token CSRF dal corpo della richiesta. La libreria GIS include questo token nel corpo della richiesta POST come parametro, denominato anche g_csrf_token.
    • Confronta i due valori dei token
      • Se entrambi i valori sono presenti e corrispondono completamente, la richiesta viene considerata legittima e proveniente dal tuo dominio.
      • Se i valori non sono presenti o non corrispondono, la richiesta deve essere rifiutata dal server. Questo controllo garantisce che la richiesta sia stata avviata da JavaScript in esecuzione sul tuo dominio, in quanto solo il tuo dominio può accedere al cookie g_csrf_token.
  2. Verifica il token ID.

    Per verificare che il token sia valido, assicurati che siano soddisfatti i seguenti criteri:

    • Il token ID è firmato correttamente da Google. Utilizza le chiavi pubbliche di Google (disponibili in formato JWK o PEM) per verificare la firma del token. Queste chiavi vengono ruotate regolarmente; esamina l'intestazione Cache-Control nella risposta per determinare quando devi recuperarle di nuovo.
    • Il valore di aud nel token ID è uguale a uno degli ID client della tua app. Questo controllo è necessario per impedire che i token ID emessi per un'app dannosa vengano utilizzati per accedere ai dati dello stesso utente sul server di backend della tua app.
    • Il valore di iss nel token ID è uguale a accounts.google.com o https://accounts.google.com.
    • Il tempo di scadenza (exp) del token ID non è ancora trascorso.
    • Se devi verificare che il token ID rappresenti un account dell'organizzazione Google Workspace o Cloud, puoi controllare l'attestazione hd, che indica il dominio ospitato dell'utente. Questo deve essere utilizzato quando si limita l'accesso a una risorsa solo ai membri di determinati domini. L'assenza di questa rivendicazione indica che l'account non appartiene a un dominio ospitato da Google.

    Utilizzando i campi email, email_verified e hd, puoi determinare se Google ospita un indirizzo email ed è autorevole per questo. Nei casi in cui Google è autorevole, l'utente è noto per essere il proprietario legittimo dell'account e puoi saltare la password o altri metodi di verifica.

    Casi in cui Google è autorevole:

    • email ha un suffisso @gmail.com, quindi è un account Gmail.
    • email_verified è vero e hd è impostato, si tratta di un account Google Workspace.

    Gli utenti possono registrarsi per gli Account Google senza utilizzare Gmail o Google Workspace. Quando email non contiene un suffisso @gmail.com e hd è assente, Google non è autorevole e si consigliano la password o altri metodi di verifica per verificare l'utente. email_verified può essere vero anche perché Google ha inizialmente verificato l'utente al momento della creazione dell'Account Google, ma la proprietà dell'account email di terze parti potrebbe essere cambiata nel frattempo.

    Anziché scrivere il tuo codice per eseguire questi passaggi di verifica, ti consigliamo vivamente di utilizzare una libreria client API di Google per la tua piattaforma o una libreria JWT generica. Per lo sviluppo e il debug, puoi chiamare il nostro endpoint di convalida tokeninfo.

    Using a Google API Client Library

    Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens in a production environment.

    Java

    To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:

    import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
    import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
    import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
    
    ...
    
    GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
        // Specify the WEB_CLIENT_ID of the app that accesses the backend:
        .setAudience(Collections.singletonList(WEB_CLIENT_ID))
        // Or, if multiple clients access the backend:
        //.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3))
        .build();
    
    // (Receive idTokenString by HTTPS POST)
    
    GoogleIdToken idToken = verifier.verify(idTokenString);
    if (idToken != null) {
      Payload payload = idToken.getPayload();
    
      // Print user identifier. This ID is unique to each Google Account, making it suitable for
      // use as a primary key during account lookup. Email is not a good choice because it can be
      // changed by the user.
      String userId = payload.getSubject();
      System.out.println("User ID: " + userId);
    
      // Get profile information from payload
      String email = payload.getEmail();
      boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
      String name = (String) payload.get("name");
      String pictureUrl = (String) payload.get("picture");
      String locale = (String) payload.get("locale");
      String familyName = (String) payload.get("family_name");
      String givenName = (String) payload.get("given_name");
    
      // Use or store profile information
      // ...
    
    } else {
      System.out.println("Invalid ID token.");
    }

    The GoogleIdTokenVerifier.verify() method verifies the JWT signature, the aud claim, the iss claim, and the exp claim.

    If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can verify the hd claim by checking the domain name returned by the Payload.getHostedDomain() method. The domain of the email claim is insufficient to ensure that the account is managed by a domain or organization.

    Node.js

    To validate an ID token in Node.js, use the Google Auth Library for Node.js. Install the library:

    npm install google-auth-library --save
    Then, call the verifyIdToken() function. For example:

    const {OAuth2Client} = require('google-auth-library');
    const client = new OAuth2Client();
    async function verify() {
      const ticket = await client.verifyIdToken({
          idToken: token,
          audience: WEB_CLIENT_ID,  // Specify the WEB_CLIENT_ID of the app that accesses the backend
          // Or, if multiple clients access the backend:
          //[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]
      });
      const payload = ticket.getPayload();
      // This ID is unique to each Google Account, making it suitable for use as a primary key
      // during account lookup. Email is not a good choice because it can be changed by the user.
      const userid = payload['sub'];
      // If the request specified a Google Workspace domain:
      // const domain = payload['hd'];
    }
    verify().catch(console.error);

    The verifyIdToken function verifies the JWT signature, the aud claim, the exp claim, and the iss claim.

    If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the hd claim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.

    PHP

    To validate an ID token in PHP, use the Google API Client Library for PHP. Install the library (for example, using Composer):

    composer require google/apiclient
    Then, call the verifyIdToken() function. For example:

    require_once 'vendor/autoload.php';
    
    // Get $id_token via HTTPS POST.
    
    $client = new Google_Client(['client_id' => $WEB_CLIENT_ID]);  // Specify the WEB_CLIENT_ID of the app that accesses the backend
    $payload = $client->verifyIdToken($id_token);
    if ($payload) {
      // This ID is unique to each Google Account, making it suitable for use as a primary key
      // during account lookup. Email is not a good choice because it can be changed by the user.
      $userid = $payload['sub'];
      // If the request specified a Google Workspace domain
      //$domain = $payload['hd'];
    } else {
      // Invalid ID token
    }

    The verifyIdToken function verifies the JWT signature, the aud claim, the exp claim, and the iss claim.

    If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the hd claim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.

    Python

    To validate an ID token in Python, use the verify_oauth2_token function. For example:

    from google.oauth2 import id_token
    from google.auth.transport import requests
    
    # (Receive token by HTTPS POST)
    # ...
    
    try:
        # Specify the WEB_CLIENT_ID of the app that accesses the backend:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(), WEB_CLIENT_ID)
    
        # Or, if multiple clients access the backend server:
        # idinfo = id_token.verify_oauth2_token(token, requests.Request())
        # if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]:
        #     raise ValueError('Could not verify audience.')
    
        # If the request specified a Google Workspace domain
        # if idinfo['hd'] != DOMAIN_NAME:
        #     raise ValueError('Wrong domain name.')
    
        # ID token is valid. Get the user's Google Account ID from the decoded token.
        # This ID is unique to each Google Account, making it suitable for use as a primary key
        # during account lookup. Email is not a good choice because it can be changed by the user.
        userid = idinfo['sub']
    except ValueError:
        # Invalid token
        pass

    The verify_oauth2_token function verifies the JWT signature, the aud claim, and the exp claim. You must also verify the hd claim (if applicable) by examining the object that verify_oauth2_token returns. If multiple clients access the backend server, also manually verify the aud claim.

  3. Una volta confermata la validità del token, puoi utilizzare le informazioni nel token ID Google per correlare lo stato dell'account del tuo sito:

    • Un utente non registrato:puoi mostrare un'interfaccia utente di registrazione che consente all'utente di fornire ulteriori informazioni sul profilo, se necessario. Consente inoltre all'utente di creare automaticamente il nuovo account e una sessione utente con accesso eseguito.

    • Un account esistente già presente nel tuo sito:puoi mostrare una pagina web che consente all'utente finale di inserire la propria password e collegare l'account legacy alle proprie credenziali Google. In questo modo viene confermato che l'utente ha accesso all'account esistente.

    • Un utente federato di ritorno:puoi accedere all'utente in modalità silenziosa.