android - 在 Android 中通过 GoogleAuthUtil 从 Google Drive API 获取访问 token

标签 android oauth-2.0 google-drive-android-api

在访问 Google Drive API 时,我在使用 GoogleAuthUtil 时遇到了一个奇怪的问题。

以下是我的代码,

    @Override
    protected String doInBackground(String... params){
        String accountName = params[0];
        //String scopes = "oauth2:profile email"; // This can work !
        String scopes = "oauth2:server:client_id:7666010xxxxx-dm0d37oxxxxxxxih8k5sm5g7tajetubk.apps.googleusercontent.com:api_scope:https://www.googleapis.com/auth/drive";
        String token = null;
        try{
            token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes);
        }
        catch (IOException e){
            Log.e(excpTAG, "IO Exception: " + e.getMessage());
        }
        catch (UserRecoverableAuthException e){
            startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
        }
        catch (GoogleAuthException e)
        {
            Log.e(excpTAG, "GoogleAuthException: " + e.getMessage());
        }
        return token;
    }

在我的实证测试中,我可以通过将范围设置为来获取用户的 Google 个人资料/电子邮件的访问 token

String scopes = "oauth2:profile email";

但是,当我想访问用户的 Google Drive 时,我按照开发文档中的说明进行操作

https://developers.google.com/accounts/docs/CrossClientAuth

并将范围设置为

String scopes = "oauth2:server:client_id:766601xxxxxx-dm0dxxxxxxxxxxxxxxxx7tajetubk.apps.googleusercontent.com:api_scope:https://www.googleapis.com/auth/drive";

应用执行时,Android-Studio中的Log猫总是提示发生了异常事件GoogleAuthException,事件消息为'Unknown'。

在 Android 中获取 Google 云端硬盘访问 token 的正确方法是什么?非常感谢。

最佳答案

终于找到答案了!

这个问题的主要原因应该是Google API Console之间的PACKAGE NAMECERTIFICATE FINGERPRINT (SHA1)不一致>安卓工作室

不一致会导致授权异常错误,在一定范围内。

Android-Studio 中的 PACKAGE NAMECERTIFICATE FINGERPRINT (SHA1)Google API Console 中的不一致时,Google API 不会简单地拒绝所有请求。 DriveScopes.Drive 等一些作用域触发了异常错误,而 oauth2:profile email 等其他作用域则没有。

在这种情况下,异常错误还会返回 Unknown 消息,误导我们修复某些范围引起的问题。

关于android - 在 Android 中通过 GoogleAuthUtil 从 Google Drive API 获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28555315/

相关文章:

android - 如何在android中为每一行设置gridlayout的背景图片?

java - 替换不敏感的子字符串,保持大小写

android - Nexus 5/Android 4.4 - 网络应用不像网络应用那样工作

javascript - chrome.identity.launchWebAuthFlow,如何清除用户缓存?

android - 无法从 Google Drive 的 App 文件夹中读取文件

android - 从 Composable 抛出异常

python - 是否可以在我的 VPS 上运行服务器的情况下从 Google 获取刷新 token ?

node.js - Passport.js 支持 'Client Credentials Flow' 吗?

android - 使用 Google Drive Api 列出 GDrive 的文件和文件夹

android - 无法使用 Intent.ACTION_GET_CONTENT 从文件选择器的 native 谷歌文档中获取字节