通过Android中的GoogleAuthUtil从Google Drive API获取访问令牌

时间:2015-02-17 05:31:43

标签: 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个人资料/电子邮件的访问令牌
String scopes = "oauth2:profile email";

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

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 cat始终提到发生了异常事件GoogleAuthException,并且事件消息为“未知”。

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

1 个答案:

答案 0 :(得分:1)

最后我找到了答案!

此问题的主要原因应该是 Google API控制台 Android-Studio 之间的PACKAGE NAMECERTIFICATE FINGERPRINT (SHA1)不一致

在某些范围内,不一致将导致授权异常错误。

Android-Studio 中的PACKAGE NAMECERTIFICATE FINGERPRINT (SHA1) Google API控制台中的DriveScopes.Driveoauth2:profile email不一致时,Google API不会简单拒绝所有请求。某些范围(例如Unknown)触发了异常错误,而其他范围(例如{{1}})则没有。

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

相关问题