Google驱动器AndroidAPI和跨客户端授权

Google Drive Android API and Cross Client Authorization

我使用 Google 驱动器 Android API 让用户从 Google 驱动器在他们的 Android 设备上上传文件到我的服务器。 我现在想更改此设置以允许我的服务器使用跨客户端授权直接访问用户 Google 驱动器,这意味着我必须使用 GoogleAuthUtil.getToken 生成 ID Token .这就是 rails 的一切。为了生成这个令牌,我需要一个 Account 对象。

目前,我正在这样设置 GoogleApiClient

mGoogleApiClient = new GoogleApiClient.Builder(getContext())
    .addApi(Drive.API)
    .addScope(Drive.SCOPE_FILE)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();

这很好用,它时不时地显示一个帐户选择器,用户可以在其中选择要连接的帐户。全部由框架管理。但是无法访问用户选择连接的 Account

相反,我必须自己管理它,使用:

Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
    false, null, null, null, null);
startActivityForResult(intent, RC_ACCOUNT_PICKER);

onActivityResult 中,我可以使用以下方法获取所选帐户:

Account account = new Account(intent.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME),
    intent.getExtras().getString(AccountManager.KEY_ACCOUNT_TYPE));

现在,因为我有一个 Account 对象,我可以使用它显式连接:

mGoogleApiClient = new GoogleApiClient.Builder(getContext())
    .addApi(Drive.API)
    .addScope(Drive.SCOPE_FILE)
    .setAccountName(mAccount.name) // Account name!
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();

这是我唯一的选择吗,真的没有办法让 Account 用户使用我的第一个解决方案选择吗?

--

稍后,在尝试生成我的 ID Token 时使用:

String scope = String.format("oauth2:server:client_id:%s:api_scope:%s",
    "12345.apps.googleusercontent.com", 
    "https://www.googleapis.com/auth/drive.file");
String token = GoogleAuthUtil.getToken(getContext(), mAccount, scope);

我仍然收到 UserRecoverableAuthException 消息,我需要获得用户的另一项许可,即使我使用的是与连接时相同的帐户和相同的授权范围。 当所有这些都处理好后,我可以再次 运行 相同的代码并最终得到我的 ID Token.

--

我是否从根本上误解了什么,或者这确实是它应该如何工作的?

您不应再使用 GoogleAuthUtil.getToken(),如 this blog post 中所述,因为将这些令牌传递到您的服务器是不安全的。

相反,您应该使用 Enable Server-Side Access via Google Sign In and use the requestServerAuthCode() method

这避免了双重提示用户,不使用 GET_ACCOUNTS 权限,并为您提供单一用户登录流程。