该示例创建一个经过身份验证的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
),但是要使用存储的acces令牌或刷新令牌。如何创建经过身份验证的HTTP客户端?使用googleapis_auth软件包?(https://pub.dartlang.org/packages/googleapis_auth)
答案 0 :(得分:0)
你已经在那里了。
您的客户端对象已包含您需要的所有内容。
这是您修改后的代码,使用存储的凭据查询空闲忙碌时间:
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());
});