google-api - 带有 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 )
解决方案
你已经在那里了。
您的客户端对象已经包含您需要的所有内容。
这是您修改后的代码,使用存储的凭据来查询 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());
});
推荐阅读
- raspberry-pi4 - raspberry pi4,hostapd 仅在 hw_mode=a (5Ghz) 下工作
- linux - 按他们的许可计算文件
- c++ - C++ 问题:[Error] 语句无法解析重载函数 x2 的地址
- c - 指针过去变量
- javascript - FULLCALENDAR:在 eventContent Hook 上获取资源
- php - laravel join 选择连接列的最大值
- javascript - 未捕获的类型错误:无法在 JS 分页/过滤项目中将显示属性设置为“块”值
- proxy - apache2服务器中动态URL的反向代理
- java - 添加超链接到内部 PDF 文件
- c++ - 是否可以直接在 Windows 上创建针对 dll 的 CMake 链接?