Google api googleapi_auth,它到底是如何工作的?

Google api googleapi_auth,它到底是如何工作的?,google-api,dart,Google Api,Dart,我正在使用Google Drive的API,我知道每次需要使用API时是否需要执行下面的代码: import“包:googleapis\u auth/auth\u browser.dart”作为gauth; 导入“package:googleapis/drive/v2.dart”作为驱动器; ... var clientid=new gauth.clientid(“xxx.apps.googleusercontent.com”,null); var scope=[drive.DriveApi.D

我正在使用Google Drive的API,我知道每次需要使用API时是否需要执行下面的代码:

import“包:googleapis\u auth/auth\u browser.dart”作为gauth;
导入“package:googleapis/drive/v2.dart”作为驱动器;
...
var clientid=new gauth.clientid(“xxx.apps.googleusercontent.com”,null);
var scope=[drive.DriveApi.DriveScope];
createImplicitBrowserFlow(clientid,scope).then((gauth.browserverAuth2Flow){
flow.ClientViaUserApprove().then((gauth.AutoRefreshingAuthClient){
var drive_api=新的drive.DriveApi(客户端);
//我的代码在这里。
}).catchError((e)=>打印(e));
});
...

一旦生成客户端变量,如果每次都不执行这些代码行,就无法恢复它?

我个人将全局保存您调用的变量drive_api(在内存中),并在我的应用程序中重新使用它(例如,我的webapp,因此在重新加载页面时它将再次运行)。一些错误(我猜当令牌需要刷新时,或者如果权限被撤销)可能需要您重新运行整个流。我认为诀窍是在页面加载后“静默”运行它

flow.clientViaUserConsent(immediate: true)
这样,如果用户已经在以前的会话中授予了权限,则将加载“drive_api”变量。例如,我通常在此时启用一些按钮

如果失败(我有时会添加一个“登录按钮”),显式调用(最好在“点击”时这样做,以允许弹出窗口出现)

立即参数的某些文档:

/// If [immediate] is `true` there will be no user involvement. If the user
/// is either not logged in or has not already granted the application access,
/// a `UserConsentException` will be thrown.
///
/// If [immediate] is `false` the user might be asked to login (if he is not
/// already logged in) and might get asked to grant the application access
/// (if the application hasn't been granted access before).

在不知道GoogleAuthAPI如何工作的情况下,您应该能够重用使用oauth生成的会话。通常,OAuth应该为您提供令牌或其他可以保存为持久数据的数据。这通常是可能的,如果有可能保存/读取持久存储的会话,您应该检查包。
/// If [immediate] is `true` there will be no user involvement. If the user
/// is either not logged in or has not already granted the application access,
/// a `UserConsentException` will be thrown.
///
/// If [immediate] is `false` the user might be asked to login (if he is not
/// already logged in) and might get asked to grant the application access
/// (if the application hasn't been granted access before).