Sunucu tarafındaki Google kimliği jetonunu doğrulama

Google Kimlik Hizmetleri veya OAuth 2.0 yetkilendirme kodu akışı kullanılırken Google, kimlik jetonunu POST yöntemiyle yönlendirme uç noktasına döndürür. Alternatif olarak, OIDC örtülü akışı bir GET isteği kullanır. Dolayısıyla, uygulamanız bu alınan kimlik bilgilerini sunucunuza güvenli bir şekilde iletmekle sorumludur.

GET

Bu, örtülü akıştır. Kimlik jetonu, URL parçası içinde döndürülür. Bu parçanın istemci tarafındaki JavaScript tarafından ayrıştırılması gerekir. Uygulamanız, isteğin kimliğinin doğruluğunu sağlamak ve CSRF gibi saldırıları önlemek için kendi doğrulama mekanizmalarını uygulamaktan sorumludur.

    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

Kimlik jetonu, credential alanı olarak geri gönderilir. GIS kitaplığı, kimlik jetonunu sunucuya göndermeye hazırlanırken otomatik olarak g_csrf_token öğesini üstbilgi çerezine ve istek gövdesine ekler. Bu, örnek bir POST isteğidir:

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. Siteler Arası İstek Sahteciliği (CSRF) saldırılarını önlemek için g_csrf_token doğrulama:

    • CSRF jetonu değerini g_csrf_token çerezinden çıkarın.
    • İstek gövdesinden CSRF jetonu değerini çıkarın. GIS kitaplığı, bu jetonu POST istek gövdesine g_csrf_token adlı bir parametre olarak ekler.
    • İki jeton değerini karşılaştırın.
      • Değerlerin her ikisi de mevcutsa ve tamamen eşleşiyorsa istek meşru kabul edilir ve alanınızdan kaynaklandığı düşünülür.
      • Değerler mevcut değilse veya eşleşmiyorsa istek sunucu tarafından reddedilmelidir. Bu kontrol, isteğin kendi alanınızda çalışan JavaScript'ten başlatıldığını doğrular. Çünkü g_csrf_token çerezine yalnızca alanınız erişebilir.
  2. Kimlik jetonunu doğrulayın.

    Jetonun geçerli olduğunu doğrulamak için aşağıdaki ölçütlerin karşılandığından emin olun:

    • Kimlik jetonu, Google tarafından düzgün şekilde imzalanmış olmalıdır. Jetonun imzasını doğrulamak için Google'ın ortak anahtarlarını (JWK veya PEM biçiminde kullanılabilir) kullanın. Bu anahtarlar düzenli olarak değiştirilir. Bunları ne zaman tekrar almanız gerektiğini belirlemek için yanıttaki Cache-Control üstbilgisini inceleyin.
    • Kimlik jetonundaki aud değeri, uygulamanızın istemci kimliklerinden birine eşittir. Bu kontrol, kötü amaçlı bir uygulamaya verilen kimlik jetonlarının, uygulamanızın arka uç sunucusunda aynı kullanıcıyla ilgili verilere erişmek için kullanılmasını önlemek amacıyla gereklidir.
    • Kimlik jetonundaki iss değeri accounts.google.com veya https://accounts.google.com'ye eşit.
    • Kimlik jetonunun geçerlilik bitiş süresi (exp) geçmedi.
    • Kimlik jetonunun bir Google Workspace veya Cloud kuruluş hesabını temsil ettiğini doğrulamanız gerekiyorsa kullanıcının barındırılan alanını belirten hd talebini kontrol edebilirsiniz. Bu, bir kaynağa erişimi yalnızca belirli alanların üyeleriyle kısıtlarken kullanılmalıdır. Bu talebin olmaması, hesabın Google tarafından barındırılan bir alana ait olmadığını gösterir.

    email, email_verified ve hd alanlarını kullanarak Google'ın bir e-posta adresini barındırıp barındırmadığını ve bu adres için yetkili olup olmadığını belirleyebilirsiniz. Google'ın yetkili olduğu durumlarda kullanıcının meşru hesap sahibi olduğu bilinir ve şifre veya diğer doğrulama yöntemlerini atlayabilirsiniz.

    Google'ın yetkili olduğu durumlar:

    • email, @gmail.com sonekini içeriyorsa bu bir Gmail hesabıdır.
    • email_verified doğruysa ve hd ayarlanmışsa bu bir Google Workspace hesabıdır.

    Kullanıcılar, Gmail veya Google Workspace kullanmadan Google Hesabı'na kaydolabilir. email, @gmail.com sonekini içermediğinde ve hd yoksa Google yetkili değildir ve kullanıcının doğrulanması için şifre veya diğer sorgulama yöntemleri önerilir. Google, Google Hesabı oluşturulurken kullanıcıyı ilk başta doğruladığı için email_verified da doğru olabilir. Ancak üçüncü taraf e-posta hesabının sahipliği o zamandan beri değişmiş olabilir.

    Bu doğrulama adımlarını gerçekleştirmek için kendi kodunuzu yazmak yerine, platformunuz için bir Google API istemci kitaplığı veya genel amaçlı bir JWT kitaplığı kullanmanızı önemle tavsiye ederiz. Geliştirme ve hata ayıklama için tokeninfo doğrulama uç noktamızı çağırabilirsiniz.

    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. Jetonun geçerliliği onaylandıktan sonra, sitenizin hesap durumunu ilişkilendirmek için Google kimlik jetonundaki bilgileri kullanabilirsiniz:

    • Kayıtlı olmayan bir kullanıcı: Gerekirse kullanıcının ek profil bilgileri sağlamasına olanak tanıyan bir kayıt kullanıcı arayüzü (UI) gösterebilirsiniz. Ayrıca, kullanıcının yeni hesabı ve oturum açmış bir kullanıcı oturumunu sessizce oluşturmasına da olanak tanır.

    • Sitenizde zaten mevcut olan bir hesap: Son kullanıcının şifresini girmesine ve eski hesabı Google kimlik bilgileriyle bağlamasına olanak tanıyan bir web sayfası gösterebilirsiniz. Bu işlem, kullanıcının mevcut hesaba erişimi olduğunu doğrular.

    • Geri dönen bir federasyon kullanıcısı: Kullanıcının oturumunu sessizce açabilirsiniz.