【问题标题】:Google authenticated HTTP client with dart带有 dart 的 Google 认证 HTTP 客户端
【发布时间】:2018-12-12 19:00:20
【问题描述】:

我已经运行了来自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);
…
…
} 

当我运行示例时,每次运行上述示例时,我都必须在网络浏览器中征得用户同意。

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

【问题讨论】:

  • 如果您的代码在服务器上运行,您可以保存访问令牌和刷新令牌。如果您的代码在客户端上运行,则无法执行此操作。但是,用户至少需要授权一次,您的代码不能请求特权范围(权限),并且您的应用必须获得 Google 的批准。基本上这意味着您的令牌将仅限于用户的姓名和电子邮件地址。

标签: google-api dart flutter google-oauth


【解决方案1】:

你已经在那里了。

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

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

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());
    });

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2017-04-09
    • 2017-10-12
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多