7

我正在按照这些说明https://developers.google.com/identity/sign-in/android/backend-auth)获取要发送到我的后端的 ID 令牌,但是当我设置时String scopes = "audience:server:client_id:" + Service.SERVER_CLIENT_ID;(是的,SERVER_CLIENT_ID这不是 Android客户 ID)我未能获得令牌并引发此错误。

E/Login: com.google.android.gms.auth.GoogleAuthException: Unknown

但是,当我改用以下范围时 String scopes = "oauth2:profile email";

我成功获得了“a”令牌,但它没有我预期的那么长,我担心它可能是错误的。

我的问题是...

1)为什么scopes = "audience:server:client_id:" + SERVER_CLIENT_ID;指南中使用的不起作用?

2) 我使用String scopes = "oauth2:profile email";安全的令牌在后端验证用户是否获得了令牌?

代码如下。

@Override
    protected String doInBackground(Void... params) {
        String accountName = Plus.AccountApi.getAccountName(googleApiClient);
        Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
        //String scopes = "oauth2:profile email";
        String scopes = "audience:server:client_id:" + Service.SERVER_CLIENT_ID; // Not the app's client ID.
        Log.d(TAG, "Account Name: " + accountName);
        Log.d(TAG, "Scopes: " + scopes);

        try {
            userIdToken = GoogleAuthUtil.getToken(getApplicationContext(), account, scopes);

            return userIdToken;
        } catch (IOException e) {
            Log.e(TAG, "IOError retrieving ID token.", e);
            return null;
        } catch (UserRecoverableAuthException e) {
            startActivityForResult(e.getIntent(), RC_SIGN_IN);
            return null;
        } catch (GoogleAuthException e) {
            Log.e(TAG, "GoogleAuthError retrieving ID token.", e);
            return null;
        }
    }
4

1 回答 1

2

当您将范围设置为 oauth2:profile 电子邮件时,您将返回一个访问令牌,该令牌不同于 id 令牌。

访问令牌可用于访问 Google API,ID 令牌是 JWT,其中包含由 Google 数字签名的用户身份信息。格式不同。如果您尝试使用为 id 令牌提供的示例代码授权访问令牌,您将收到无效错误。

如果您查看 GoogleAuthUtil.getToken() 的文档,您会发现 GoogleAuthException 是一个致命异常,通常由无效范围或无效客户端等客户端错误引起。 https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil#getToken(android.content.Context, android.accounts.Account, java.lang.String, android.os.捆)

确保您已在 Google Developer 控制台中设置了 App 和 Webserver oAuth2 ID,并且清单中的包名称与您在创建 App ID 时提供的包名称以及 SHA 指纹匹配。使用 Web 服务器 ID 作为 SERVER_CLIENT_ID。

我上传了一些示例代码到 Github。https://github.com/kmosdev/google-signin-backend-auth

我从 Google 的示例登录应用开始,并对其进行了修改以添加后端身份验证。更多详细信息在自述文件中。

要检查的另一件事是您在清单文件中具有正确的权限,但我相信如果这是错误的,您会收到不同的错误:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
于 2015-10-15T15:16:54.627 回答