为什么 requestIdToken 返回 null?

why is requestIdToken returning null?

我关注了below steps as this link

  1. 我已将 google-services.json 下载到我的应用程序文件夹。
  2. 我的项目级别gradle文件:

    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.google.gms:google-services:1.5.0-beta2'
    }
    
  3. 我的应用等级gradle 文件:

    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.google.android.gms:play-services-identity:8.3.0'
        compile 'com.google.android.gms:play-services:8.3.0'
        compile 'com.google.android.gms:play-services-plus:8.3.0'
        compile 'com.google.android.gms:play-services-auth:8.3.0'
        ...
    }
    
  4. 我为后端服务器创建了 OAuth 2.0 客户端 ID,并将此客户端 ID 传递到 strings.xml 文件。

  5. 最后我创建了 GoogleSignInOptions 和 GoogleApiClient 对象,如下所示:

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.server_client_id))
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    

    但问题是 result.isSuccess() 在 handleSignInResult 函数中总是 returns false。我在想也许我在第一步或第二步做错了什么。我的代码几乎与此相似SignInActivity.java。如有任何帮助,我们将不胜感激。

正如我对以下问题的回答:

为了成功请求 Id Token,您应该使用 "Web application" 类型的客户端 ID,而不是 "Android" 类型的客户端 ID。

您还可以在 Google's documentation 找到以下信息(请注意 #3):

Create an OAuth 2.0 client ID for your backend server

If your app authenticates with a backend server or accesses Google APIs from your backend server, you must create an OAuth 2.0 client ID for your server. To create an OAuth 2.0 client ID:

  1. Open the Credentials page.
  2. Click Add credentials > OAuth 2.0 client ID.
  3. Select Web application.
  4. Click Create.

Pass this client ID to the requestIdToken or requestServerAuthCode method when you create the GoogleSignInOptions object.


3 月 26 日更新:

Android Developers Blog - Registering OAuth clients for Google Sign-In

就我而言,我以前y,

 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

我通过添加 requestToken 方法修复了它,

 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.default_web_client_id))
            .build();

现在它适用于 me.Hopefully 这可以帮助像我这样有问题的人。

我们可以将 requestServerAuthCode 方法与 "WebApplication ClientID" 一起使用,并创建一个方法来获取访问令牌,如下所示;

 new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)

                    .requestServerAuthCode("WEBAPPLICATION CLIENT ID")

                    .requestEmail()

                    .build())

如上所示,我们需要一个 WEBAPPLICATION CLIENT ID,我们可以从 https://console.developers.google.com;

obtain web application client id as follows

void fetchGoogleAuthToken(){

    OkHttpClient okHttpclient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder()
            .add("grant_type", "authorization_code")
            .add("client_id", "812741506391-
              h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com")
            .add("client_secret", "{clientSecret}")
            .add("redirect_uri","")
            .add("code", "4/4-GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8")
            .build();

    final Request request = new Request.Builder()
            .url("https://www.googleapis.com/oauth2/v4/token")
            .post(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Log.e(LOG_TAG, e.toString());                
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                JSONObject jsonObject = new 
                             JSONObject(response.body().string());
                final String message = jsonObject.toString(5);
                Log.i(LOG_TAG, message);                    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

请使用编译'com.squareup.okhttp:okhttp:2.6.0'(ver 3-RC1会有不同类)或者你可以使用任何网络框架进行上述调用

响应成功后,您将在 log-cat 中获得以下信息:

I/onResponse: {
          "expires_in": 3600,

          "token_type": "Bearer",

          "refresh_token": "1\/xz1eb0XU3....nxoALEVQ",

          "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQxMWY1Ym......yWVsUA",

     **"access_token": "ya29.bQKKYah-........_tkt980_qAGIo9yeWEG4"**
     }

可以看到 acces_token 可以进一步使用。

我遇到了同样的问题。我所做的只是再次下载 google-services.json 文件,替换旧文件,然后就可以了。 不知道为什么会这样,我的猜测是发生了一些变化,在覆盖之前我忘记比较了。