बैकएंड सर्वर से पुष्टि करें

अगर किसी ऐसे ऐप्लिकेशन या साइट के साथ 'Google साइन इन' का इस्तेमाल किया जाता है जो बैकएंड सर्वर के साथ कम्यूनिकेट करता है, तो आपको सर्वर पर साइन इन किए हुए मौजूदा उपयोगकर्ता की पहचान करनी पड़ सकती है. सुरक्षित तरीके से साइन इन करने के लिए, जब कोई उपयोगकर्ता साइन इन कर ले, तब एचटीटीपीएस का इस्तेमाल करके, अपने सर्वर पर उपयोगकर्ता का आईडी टोकन भेजें. इसके बाद, सर्वर पर इस बात की पुष्टि करें कि आईडी टोकन सही है या नहीं. साथ ही, सेशन बनाने या नया खाता बनाने के लिए, टोकन में मौजूद उपयोगकर्ता की जानकारी का इस्तेमाल करें.

अपने सर्वर पर आईडी टोकन भेजें

उपयोगकर्ता के साइन इन करने के बाद, उपयोगकर्ता का आईडी टोकन पाएं:

Swift

GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
    guard error == nil else { return }
    guard let signInResult = signInResult else { return }

    signInResult.user.refreshTokensIfNeeded { user, error in
        guard error == nil else { return }
        guard let user = user else { return }

        let idToken = user.idToken
        // Send ID token to backend (example below).
    }
}

Objective-C

[GIDSignIn.sharedInstance signInWithPresentingViewController:self
                                              completion:^(GIDSignInResult * _Nullable signInResult,
                                                           NSError * _Nullable error) {
      if (error) { return; }
      if (signInResult == nil) { return; }

      [signInResult.user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                               NSError * _Nullable error) {
          if (error) { return; }
          if (user == nil) { return; }

          NSString *idToken = user.idToken;
          // Send ID token to backend (example below).
      }];
}];

इसके बाद, एचटीटीपीएस पोस्ट अनुरोध के साथ अपने सर्वर पर आईडी टोकन भेजें:

Swift

func tokenSignInExample(idToken: String) {
    guard let authData = try? JSONEncoder().encode(["idToken": idToken]) else {
        return
    }
    let url = URL(string: "https://yourbackend.example.com/tokensignin")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.uploadTask(with: request, from: authData) { data, response, error in
        // Handle response from your backend.
    }
    task.resume()
}

Objective-C

NSString *signinEndpoint = @"https://yourbackend.example.com/tokensignin";
NSDictionary *params = @{@"idtoken": idToken};

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:signinEndpoint];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:queue
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                         if (error) {
                           NSLog(@"Error: %@", error.localizedDescription);
                         } else {
                           NSLog(@"Signed in as %@", data.bytes);
                         }
                       }];

पुष्टि करना कि आईडी टोकन सही है या नहीं

एचटीटीपीएस POST से आईडी टोकन मिलने के बाद, आपको इसकी पुष्टि करनी होगी कि टोकन सही है या नहीं.

To verify that the token is valid, ensure that the following criteria are satisfied:

  • The ID token is properly signed by Google. Use Google's public keys (available in JWK or PEM format) to verify the token's signature. These keys are regularly rotated; examine the Cache-Control header in the response to determine when you should retrieve them again.
  • The value of aud in the ID token is equal to one of your app's client IDs. This check is necessary to prevent ID tokens issued to a malicious app being used to access data about the same user on your app's backend server.
  • The value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
  • The expiry time (exp) of the ID token has not passed.
  • 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.

Rather than writing your own code to perform these verification steps, we strongly recommend using a Google API client library for your platform, or a general-purpose JWT library. For development and debugging, you can call our tokeninfo validation endpoint.

Google API क्लाइंट लाइब्रेरी का इस्तेमाल करना

प्रोडक्शन एनवायरमेंट में, Google आईडी टोकन की पुष्टि करने के लिए, Google API क्लाइंट लाइब्रेरी में से किसी एक का इस्तेमाल करने का सुझाव दिया जाता है. जैसे, Java, Node.js, PHP, Python.

JavaScript

Java में किसी आईडी टोकन की पुष्टि करने के लिए, GoogleIdTokenVerifier ऑब्जेक्ट का इस्तेमाल करें. उदाहरण के लिए:

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 CLIENT_ID of the app that accesses the backend:
    .setAudience(Collections.singletonList(CLIENT_ID))
    // Or, if multiple clients access the backend:
    //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
    .build();

// (Receive idTokenString by HTTPS POST)

GoogleIdToken idToken = verifier.verify(idTokenString);
if (idToken != null) {
  Payload payload = idToken.getPayload();

  // Print user identifier
  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.");
}

GoogleIdTokenVerifier.verify() का इस्तेमाल, JWT के हस्ताक्षर, aud दावे, iss दावे, और exp दावे की पुष्टि करता है.

अगर आपको यह पुष्टि करनी है कि आईडी टोकन, Google Workspace या Cloud संगठन के खाते से जुड़ा है, तो hd दावे की पुष्टि करें. इसके लिए, Payload.getHostedDomain() तरीके से लौटाए गए डोमेन नेम की जांच करें. email दावे वाले डोमेन की वजह से, यह पक्का नहीं किया जा सकता कि खाते को किसी डोमेन या संगठन से मैनेज किया जा रहा है या नहीं.

Node.js

Node.js में किसी आईडी टोकन की पुष्टि करने के लिए, Node.js के लिए Google Auth लाइब्रेरी का इस्तेमाल करें. लाइब्रेरी इंस्टॉल करें:

npm install google-auth-library --save
इसके बाद, verifyIdToken() फ़ंक्शन को कॉल करें. उदाहरण के लिए:

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client();
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If the request specified a Google Workspace domain:
  // const domain = payload['hd'];
}
verify().catch(console.error);

verifyIdToken फ़ंक्शन, JWT हस्ताक्षर, aud दावे, exp दावे, और iss दावे की पुष्टि करता है.

अगर आपको इस बात की पुष्टि करनी है कि आईडी टोकन, Google Workspace या Cloud संगठन के खाते के बारे में बताता है, तो hd दावा देखें. इससे पता चलता है कि उपयोगकर्ता का होस्ट किया गया डोमेन क्या है. किसी संसाधन के ऐक्सेस को सिर्फ़ कुछ डोमेन के सदस्यों तक सीमित करते समय, इसका इस्तेमाल करना चाहिए. इस दावे के न होने का मतलब है कि यह खाता, Google के होस्ट किए गए डोमेन से नहीं जुड़ा है.

फ़िलिपींस

PHP में किसी आईडी टोकन की पुष्टि करने के लिए, PHP के लिए Google एपीआई क्लाइंट लाइब्रेरी का इस्तेमाल करें. लाइब्रेरी इंस्टॉल करें (उदाहरण के लिए, कंपोज़र का इस्तेमाल करके):

composer require google/apiclient
इसके बाद, verifyIdToken() फ़ंक्शन को कॉल करें. उदाहरण के लिए:

require_once 'vendor/autoload.php';

// Get $id_token via HTTPS POST.

$client = new Google_Client(['client_id' => $CLIENT_ID]);  // Specify the CLIENT_ID of the app that accesses the backend
$payload = $client->verifyIdToken($id_token);
if ($payload) {
  $userid = $payload['sub'];
  // If the request specified a Google Workspace domain
  //$domain = $payload['hd'];
} else {
  // Invalid ID token
}

verifyIdToken फ़ंक्शन, JWT हस्ताक्षर, aud दावे, exp दावे, और iss दावे की पुष्टि करता है.

अगर आपको इस बात की पुष्टि करनी है कि आईडी टोकन, Google Workspace या Cloud संगठन के खाते के बारे में बताता है, तो hd दावा देखें. इससे पता चलता है कि उपयोगकर्ता का होस्ट किया गया डोमेन क्या है. किसी संसाधन के ऐक्सेस को सिर्फ़ कुछ डोमेन के सदस्यों तक सीमित करते समय, इसका इस्तेमाल करना चाहिए. इस दावे के न होने का मतलब है कि यह खाता, Google के होस्ट किए गए डोमेन से नहीं जुड़ा है.

Python

Python में किसी आईडी टोकन की पुष्टि करने के लिए, verify_oauth2_token फ़ंक्शन का इस्तेमाल करें. उदाहरण के लिए:

from google.oauth2 import id_token
from google.auth.transport import requests

# (Receive token by HTTPS POST)
# ...

try:
    # Specify the CLIENT_ID of the app that accesses the backend:
    idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)

    # Or, if multiple clients access the backend server:
    # idinfo = id_token.verify_oauth2_token(token, requests.Request())
    # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, 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.
    userid = idinfo['sub']
except ValueError:
    # Invalid token
    pass

verify_oauth2_token फ़ंक्शन, JWT के हस्ताक्षर, aud दावे, और exp दावे की पुष्टि करता है. आपको hd दावे (अगर लागू हो) की पुष्टि भी करनी होगी. इसके लिए, verify_oauth2_token से मिले ऑब्जेक्ट की जांच करें. अगर एक से ज़्यादा क्लाइंट बैकएंड सर्वर को ऐक्सेस करते हैं, तो aud के दावे की मैन्युअल तरीके से भी पुष्टि करें.

Calling the tokeninfo endpoint

An easy way to validate an ID token signature for debugging is to use the tokeninfo endpoint. Calling this endpoint involves an additional network request that does most of the validation for you while you test proper validation and payload extraction in your own code. It is not suitable for use in production code as requests may be throttled or otherwise subject to intermittent errors.

To validate an ID token using the tokeninfo endpoint, make an HTTPS POST or GET request to the endpoint, and pass your ID token in the id_token parameter. For example, to validate the token "XYZ123", make the following GET request:

https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123

If the token is properly signed and the iss and exp claims have the expected values, you will get a HTTP 200 response, where the body contains the JSON-formatted ID token claims. Here's an example response:

{
 // These six fields are included in all Google ID Tokens.
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953",

 // These seven fields are only included when the user has granted the "profile" and
 // "email" OAuth scopes to the application.
 "email": "testuser@gmail.com",
 "email_verified": "true",
 "name" : "Test User",
 "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
 "given_name": "Test",
 "family_name": "User",
 "locale": "en"
}

If you need to validate that the ID token represents a Google Workspace 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 Workspace hosted domain.

खाता या सेशन बनाएं

टोकन की पुष्टि करने के बाद, देखें कि उपयोगकर्ता पहले से आपके उपयोगकर्ता डेटाबेस में है या नहीं. अगर हां, तो उपयोगकर्ता के लिए एक पुष्टि किया गया सेशन तय करें. अगर उपयोगकर्ता अब तक आपके उपयोगकर्ता डेटाबेस में नहीं है, तो आईडी टोकन पेलोड की जानकारी से एक नया उपयोगकर्ता रिकॉर्ड बनाएं और उपयोगकर्ता के लिए एक सेशन बनाएं. अगर आपको अपने ऐप्लिकेशन में किसी नए उपयोगकर्ता का पता चलता है, तो उपयोगकर्ता को प्रोफ़ाइल से जुड़ी ऐसी अतिरिक्त जानकारी देने के लिए कहा जा सकता है जिसकी ज़रूरत हो.

'सभी खातों की सुरक्षा' सुविधा की मदद से उपयोगकर्ताओं के खातों को सुरक्षित रखना

अगर किसी उपयोगकर्ता के खाते में साइन इन करने के लिए Google पर भरोसा किया जाता है, तो आपको अपने-आप उन सभी सुरक्षा सुविधाओं और इन्फ़्रास्ट्रक्चर का फ़ायदा मिलेगा जिन्हें Google ने, उपयोगकर्ता के डेटा की सुरक्षा के लिए बनाया है. हालांकि, अगर उपयोगकर्ता के Google खाते से छेड़छाड़ होने की कोई संभावना नहीं है या सुरक्षा से जुड़ी किसी दूसरी अहम गतिविधि का पता चलता है, तो आपके ऐप्लिकेशन पर हमले का खतरा भी हो सकता है. अपने खातों को सुरक्षा से जुड़ी किसी भी बड़ी गतिविधि से बचाने के लिए, सभी खातों की सुरक्षा सुविधा का इस्तेमाल करें. इससे आपको Google से सुरक्षा से जुड़ी चेतावनियां मिलती हैं. इस तरह के इवेंट मिलने पर, आपको उपयोगकर्ता के Google खाते की सुरक्षा से जुड़े अहम बदलावों की जानकारी मिलती है. इसके बाद, अपने खातों को सुरक्षित रखने के लिए अपनी सेवा पर कार्रवाई की जा सकती है.