Zweryfikuj token identyfikatora Google po stronie serwera

Gdy używasz usług tożsamości Google lub procesu kodu autoryzacji OAuth 2.0, Google zwraca token identyfikatora za pomocą metody POST do punktu końcowego przekierowania. Alternatywnie niejawny przepływ OIDC używa żądania GET. W związku z tym Twoja aplikacja jest odpowiedzialna za bezpieczne przesyłanie otrzymanych danych logowania na serwer.

GET

Jest to przepływ niejawny. Token identyfikatora jest zwracany we fragmencie adresu URL, który musi zostać przeanalizowany przez JavaScript po stronie klienta. Twoja aplikacja jest odpowiedzialna za wdrożenie własnych mechanizmów weryfikacji, które zapewnią autentyczność żądania i zapobiegną atakom takim jak 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

Token identyfikacji jest odsyłany w polu credential. Podczas przygotowywania tokena identyfikatora do wysłania na serwer biblioteka GIS automatycznie dodaje znak g_csrf_token do pliku cookie nagłówka i treści żądania. Oto przykładowe żądanie POST:

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. Weryfikacja g_csrf_token, aby zapobiegać atakom typu CSRF (Cross-Site Request Forgery):

    • Wyodrębnij wartość tokena CSRF z pliku cookie g_csrf_token.
    • Wyodrębnij wartość tokena CSRF z treści żądania. Biblioteka GIS uwzględnia ten token w treści żądania POST jako parametr o nazwie g_csrf_token.
    • Porównaj 2 wartości tokenów.
      • Jeśli obie wartości są obecne i całkowicie zgodne, żądanie jest uznawane za prawidłowe i pochodzące z Twojej domeny.
      • Jeśli wartości nie są obecne lub nie pasują, serwer musi odrzucić żądanie. Ten test zapewnia, że żądanie zostało zainicjowane przez kod JavaScript działający w Twojej domenie, ponieważ tylko Twoja domena ma dostęp do pliku cookie g_csrf_token.
  2. Zweryfikuj token identyfikatora.

    Aby sprawdzić, czy token jest prawidłowy, upewnij się, że spełnia te kryteria:

    • Token identyfikacji jest prawidłowo podpisany przez Google. Użyj kluczy publicznych Google (dostępnych w formacie JWK lub PEM), aby zweryfikować podpis tokena. Te klucze są regularnie zmieniane. Sprawdź nagłówek Cache-Control w odpowiedzi, aby określić, kiedy należy je ponownie pobrać.
    • Wartość aud w tokenie identyfikatora jest równa jednemu z identyfikatorów klienta Twojej aplikacji. Jest to konieczne, aby zapobiec używaniu tokenów identyfikatora wydanych złośliwej aplikacji do uzyskiwania dostępu do danych o tym samym użytkowniku na serwerze backendu aplikacji.
    • Wartość iss w tokenie identyfikatora jest równa accounts.google.com lub https://accounts.google.com.
    • Czas wygaśnięcia tokena identyfikacyjnego (exp) jeszcze nie upłynął.
    • Jeśli musisz sprawdzić, czy token identyfikatora reprezentuje konto organizacji Google Workspace lub Cloud, możesz sprawdzić roszczenie hd, które wskazuje hostowaną domenę użytkownika. Należy go używać, gdy chcesz ograniczyć dostęp do zasobu tylko do członków określonych domen. Brak tego roszczenia oznacza, że konto nie należy do domeny hostowanej przez Google.

    Korzystając z pól email, email_verified i hd, możesz sprawdzić, czy Google hostuje adres e-mail i czy jest dla niego autorytatywny. W przypadkach, w których Google ma wiarygodne informacje, użytkownik jest uznawany za prawowitego właściciela konta i możesz pominąć hasło lub inne metody weryfikacji.

    Sytuacje, w których Google jest miarodajne:

    • email ma sufiks @gmail.com, jest to konto Gmail.
    • email_verified jest prawdziwe i hd jest ustawione, jest to konto Google Workspace.

    Użytkownicy mogą rejestrować konta Google bez używania Gmaila ani Google Workspace. Gdy email nie zawiera sufiksu @gmail.com i nie ma parametru hd, Google nie jest autorytatywny i zaleca się użycie hasła lub innych metod weryfikacji użytkownika. email_verified może być też prawdziwe, ponieważ Google początkowo zweryfikowało użytkownika podczas tworzenia konta Google, ale od tego czasu własność konta e-mail w usłudze innej firmy mogła ulec zmianie.

    Zamiast pisać własny kod do wykonywania tych kroków weryfikacji, zdecydowanie zalecamy używanie biblioteki klienta interfejsu Google API dla Twojej platformy lub ogólnej biblioteki JWT. Na potrzeby programowania i debugowania możesz wywołać nasz tokeninfopunkt końcowy weryfikacji.

    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. Po potwierdzeniu ważności tokena możesz użyć informacji z tokena identyfikatora Google, aby powiązać stan konta w Twojej witrynie:

    • Niezarejestrowany użytkownik: możesz wyświetlić interfejs rejestracji, który umożliwia użytkownikowi podanie dodatkowych informacji o profilu, jeśli jest to wymagane. Umożliwia też użytkownikowi ciche utworzenie nowego konta i sesji zalogowanego użytkownika.

    • Istniejące konto, które jest już w Twojej witrynie: możesz wyświetlić stronę internetową, na której użytkownik może wpisać hasło i połączyć starsze konto z danymi logowania Google. Potwierdza to, że użytkownik ma dostęp do istniejącego konta.

    • Powracający użytkownik federacyjny: możesz zalogować go w sposób niewidoczny.