सर्वर-साइड ऐक्सेस चालू करना

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

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

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

  1. 'Google साइन-इन' को कॉन्फ़िगर करने पर, requestServerAuthCode तरीके की मदद से GoogleSignInOptions ऑब्जेक्ट बनाएं. साथ ही, यह तय करें कि आपके ऐप्लिकेशन के बैकएंड को requestScopes तरीके से, किन स्कोप को ऐक्सेस करने की ज़रूरत है.

    अपने सर्वर का क्लाइंट आईडी requestServerAuthCode तरीके से पास करें.

    // Configure sign-in to request offline access to the user's ID, basic
    // profile, and Google Drive. The first time you request a code you will
    // be able to exchange it for an access token and refresh token, which
    // you should store. In subsequent calls, the code will only result in
    // an access token. By asking for profile access (through
    // DEFAULT_SIGN_IN) you will also get an ID Token as a result of the
    // code exchange.
    String serverClientId = getString(R.string.server_client_id);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
            .requestServerAuthCode(serverClientId)
            .requestEmail()
            .build();
  2. जब उपयोगकर्ता सफलता से साइन इन कर लेता है, तब getServerAuthCode वाले उपयोगकर्ता की पुष्टि करने से जुड़ा कोड पाएं:

    Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
    try {
        GoogleSignInAccount account = task.getResult(ApiException.class);
        String authCode = account.getServerAuthCode();
    
        // Show signed-un UI
        updateUI(account);
    
        // TODO(developer): send code to server and exchange for access/refresh/ID tokens
    } catch (ApiException e) {
        Log.w(TAG, "Sign-in failed", e);
        updateUI(null);
    }
  3. एचटीटीपीएस POST का इस्तेमाल करके, अपने ऐप्लिकेशन के बैकएंड में पुष्टि करने वाला कोड भेजें:

    HttpPost httpPost = new HttpPost("https://yourbackend.example.com/authcode");
    
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("authCode", authCode));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        final String responseBody = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        Log.e(TAG, "Error sending auth code to backend.", e);
    } catch (IOException e) {
        Log.e(TAG, "Error sending auth code to backend.", e);
    }
    
  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']