首页 > 解决方案 > 带有 dart 的 Google 认证 HTTP 客户端

问题描述

我已经运行了来自https://github.com/dart-lang/googleapis_examples/blob/master/drive_upload_download_console/bin/main.dart的示例。

该示例创建了一个经过身份验证的 HTTP 客户端,用于访问 Google Drive API:

import 'package:googleapis_auth/auth_io.dart' as auth;
…
…  

auth.clientViaUserConsent(identifier, scopes, userPrompt).then((client) {   // with client_id, client_secret, scope
  var api = new drive.DriveApi(client);
…
…
} 

当我运行示例时,每次运行上面的示例时,我都必须在 Web 浏览器中给予用户同意。

我想创建一个经过身份验证的 HTTP 客户端,而不必使用用户同意函数 ( auth.clientViaUserConsent),而是使用存储的访问令牌或刷新令牌。如何创建这样一个经过身份验证的 HTTP 客户端?使用 googleapis_auth 包?( https://pub.dartlang.org/packages/googleapis_auth )

标签: google-apidartfluttergoogle-oauth

解决方案


你已经在那里了。

您的客户端对象已经包含您需要的所有内容。

这是您修改后的代码,使用存储的凭据来查询 freeBusy 时间:

auth.clientViaUserConsent(identifier, scopes, userPrompt).then((client) {   // with client_id, client_secret, scope
  var api = new drive.DriveApi(client);
  debugPrint(' access token: ' + client.credentials.accessToken.data +' refresh token ' + client.credentials.refreshToken);
  // store the tokens in the apps key store 
}

在将来的某个时间进行新的调用以从永不过期的刷新令牌中获取新的访问凭据,并为您的目的创建一个新客户端。

    AccessCredentials _fromStorage = AccessCredentials(client.credentials.accessToken, 
    client.credentials.refreshToken, _scopes );

    var _newClient = new http.Client();
    AccessCredentials _accessCredentials = await refreshCredentials( _clientID, _fromStorage , _newClient);
    _newClient = authenticatedClient(_newClient, _accessCredentials);
    // the code below was just for me to test this out with my API scopes. replace with your code

    var calendar = cal.CalendarApi(_newClient);
    String calendarId = "---some string---";
    cal.FreeBusyRequest _request = cal.FreeBusyRequest.fromJson(
        {
          'items': [
            {'id': calendarId, 'busy': 'Active'}
          ],
          'timeMin': (new DateTime(2020, 11, 17)).toIso8601String()+'Z',
          'timeMax': (new DateTime(2020, 11, 19)).toIso8601String()+'Z'
        });
      debugPrint('request: ' + _request.toJson().toString());
      cal.FreeBusyResponse response = await calendar.freebusy.query(_request);
      debugPrint(response.toJson().toString());
    });

推荐阅读