googleapi_auth,它是如何工作的?

时间:2014-11-21 08:50:14

标签: google-api dart

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

import "package:googleapis_auth/auth_browser.dart" as gauth;
import "package:googleapis/drive/v2.dart" as drive;
...
  var clientid = new gauth.ClientId("xxx.apps.googleusercontent.com", null);
  var scope = [drive.DriveApi.DriveScope];

  gauth.createImplicitBrowserFlow(clientid, scope).then((gauth.BrowserOAuth2Flow flow) {
    flow.clientViaUserConsent().then((gauth.AutoRefreshingAuthClient client) {
      var drive_api = new drive.DriveApi(client);
      // My code here.
      }).catchError((e) => print(e));
  });
...

生成客户端var后,无法每次都执行这些代码行而无法恢复它吗?

1 个答案:

答案 0 :(得分:2)

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

flow.clientViaUserConsent(immediate: true)

通过这样做,如果用户已在先前会话中授予权限,则将加载“drive_api”变量。例如,我通常在此时启用一些按钮

如果失败(我有时添加“登录按钮”),请明确调用(最好在“点击”上执行此操作以允许弹出窗口显示)

flow.clientViaUserConsent()

立即参数的一些文档:

/// 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).