Google 使用后端服务器进行身份验证所需的范围

Google Authentication with a Backend Server required Scopes

我正在关注 these instructions (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;
        }
    }

当您将范围设置为 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.Bundle)

确保您已在 Google 开发者控制台中设置应用程序和网络服务器 oAuth2 ID,并且清单中的包名称与您在创建应用程序时提供的包名称以及 SHA 指纹相匹配ID。使用网络服务器 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" />