अपने ऐप्लिकेशन बैकएंड से Google API ऐक्सेस करें

अगर आप चाहते हैं कि आपके सर्वर, उपयोगकर्ताओं की ओर से या उनके ऑफ़लाइन होने पर, Google API कॉल कर सकें, तो यह तरीका अपनाएं.

शुरू करने से पहले

आपको 'Google साइन इन' का बुनियादी इंटिग्रेशन पूरा करना होगा.

अपने ऐप्लिकेशन के लिए सर्वर साइड एपीआई ऐक्सेस चालू करें

iOS ऐप्लिकेशन में Google API को ऐक्सेस करना पेज पर, आपका ऐप्लिकेशन सिर्फ़ क्लाइंट साइड पर उपयोगकर्ता की पुष्टि करता है. ऐसे में, आपका ऐप्लिकेशन Google API को सिर्फ़ तब ऐक्सेस कर पाएगा, जब उपयोगकर्ता लगातार आपके ऐप्लिकेशन का इस्तेमाल कर रहा हो.

इस पेज पर बताई गई प्रक्रिया की मदद से, आपके सर्वर, उपयोगकर्ताओं के ऑफ़लाइन होने पर उनकी ओर से Google API कॉल कर सकते हैं. उदाहरण के लिए, कोई फ़ोटो ऐप्लिकेशन किसी फ़ोटो को बैकएंड सर्वर पर प्रोसेस करके और नतीजे को दूसरे एल्बम में अपलोड करके, उपयोगकर्ता के Google Photos एल्बम में फ़ोटो को बेहतर बना सकता है. ऐसा करने के लिए, आपके सर्वर को ऐक्सेस टोकन और रीफ़्रेश टोकन की ज़रूरत होगी.

अपने सर्वर के लिए ऐक्सेस टोकन पाने और रीफ़्रेश टोकन पाने के लिए, एक बार इस्तेमाल होने वाले ऑथराइज़ेशन कोड का अनुरोध किया जा सकता है, जिसे आपका सर्वर इन दो टोकन के लिए एक्सचेंज करता है. साइन इन करने के बाद, आपको GIDSignInResult की serverAuthCode प्रॉपर्टी के तौर पर, एक बार इस्तेमाल होने वाला कोड मिलेगा.

  1. अगर आपने पहले से ऐसा नहीं किया है, तो सर्वर क्लाइंट आईडी पाएं और अपने ऐप्लिकेशन की Info.plist फ़ाइल में, अपने OAuth क्लाइंट आईडी के नीचे इसकी जानकारी दें.

    <key>GIDServerClientID</key>
    <string>YOUR_SERVER_CLIENT_ID</string>
    

  2. अपने साइन-इन कॉलबैक में, एक बार इस्तेमाल किया जाने वाला ऑथराइज़ेशन कोड वापस पाएं:

    Swift

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

    Objective-C

    [GIDSignIn.sharedInstance
              signInWithPresentingViewController:self
                                      completion:^(GIDSignInResult * _Nullable signInResult,
                                                   NSError * _Nullable error) {
          if (error) { return; }
          if (signInResult == nil) { return; }
    
          NSString *authCode = signInResult.serverAuthCode;
    }];
    
  3. एचटीटीपीएस पोस्ट का इस्तेमाल करके, serverAuthCode स्ट्रिंग को अपने सर्वर पर सुरक्षित तरीके से पास करें.

  4. अपने ऐप्लिकेशन के बैकएंड सर्वर पर, ऐक्सेस के लिए ऑथराइज़ेशन कोड को एक-दूसरे से बदलें और टोकन रीफ़्रेश करें. उपयोगकर्ता की ओर से Google API को कॉल करने के लिए, ऐक्सेस टोकन का इस्तेमाल करें. साथ ही, ऐक्सेस टोकन की समयसीमा खत्म होने पर नया ऐक्सेस टोकन पाने के लिए, रीफ़्रेश टोकन सेव करें.

    उदाहरण के लिए:

    Java
    // (Receive authCode via HTTPS POST)
    
    
    if (request.getHeader("X-Requested-With") == null) {
      // Without the `X-Requested-With` header, this request could be forged. Aborts.
    }
    
    // Set path to the Web application client_secret_*.json file you downloaded from the
    // Google API Console: https://console.cloud.google.com/apis/credentials
    // You can also find your Web application client ID and client secret from the
    // console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
    // object.
    String CLIENT_SECRET_FILE = "/path/to/client_secret.json";
    
    // Exchange auth code for access token
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(
            JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
    GoogleTokenResponse tokenResponse =
              new GoogleAuthorizationCodeTokenRequest(
                  new NetHttpTransport(),
                  JacksonFactory.getDefaultInstance(),
                  "https://oauth2.googleapis.com/token",
                  clientSecrets.getDetails().getClientId(),
                  clientSecrets.getDetails().getClientSecret(),
                  authCode,
                  REDIRECT_URI)  // Specify the same redirect URI that you use with your web
                                 // app. If you don't have a web version of your app, you can
                                 // specify an empty string.
                  .execute();
    
    String accessToken = tokenResponse.getAccessToken();
    
    // Use access token to call API
    GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
    Drive drive =
        new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
            .setApplicationName("Auth Code Exchange Demo")
            .build();
    File file = drive.files().get("appfolder").execute();
    
    // Get profile info from ID token
    GoogleIdToken idToken = tokenResponse.parseIdToken();
    GoogleIdToken.Payload payload = idToken.getPayload();
    String userId = payload.getSubject();  // Use this value as a key to identify a user.
    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");
    
    Python
    from apiclient import discovery
    import httplib2
    from oauth2client import client
    
    # (Receive auth_code by HTTPS POST)
    
    
    # If this request does not have `X-Requested-With` header, this could be a CSRF
    if not request.headers.get('X-Requested-With'):
        abort(403)
    
    # Set path to the Web application client_secret_*.json file you downloaded from the
    # Google API Console: https://console.cloud.google.com/apis/credentials
    CLIENT_SECRET_FILE = '/path/to/client_secret.json'
    
    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)
    
    # Call Google API
    http_auth = credentials.authorize(httplib2.Http())
    drive_service = discovery.build('drive', 'v3', http=http_auth)
    appfolder = drive_service.files().get(fileId='appfolder').execute()
    
    # Get profile info from ID token
    userid = credentials.id_token['sub']
    email = credentials.id_token['email']