melomg
melomg

Reputation: 748

why is requestIdToken returning null?

I followed below steps as this link

  1. I downloaded google-services.json to my app folder.
  2. My project level gradle file :

    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.google.gms:google-services:1.5.0-beta2'
    }
    
  3. My app level gradle file :

    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. I created OAuth 2.0 client ID for my backend server and pass this Client ID to strings.xml file.

  5. And finally I created GoogleSignInOptions and GoogleApiClient objects as below :

    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();
    

    But the problem is result.isSuccess() always returns false in handleSignInResult function. I'm thinking maybe I'm doing somethings wrongly in 1th or 2nd step. And my codes are almost similar to this SignInActivity.java. Any help would be appreciated.

Upvotes: 28

Views: 34376

Answers (4)

Doilio Matsinhe
Doilio Matsinhe

Reputation: 2280

I was facing the same issue. All I did was simply download the google-services.json file again, replaced the old one and it worked. Don't know why this happened, my guess is something changed, And before Overwriting I forgot to compare.

Upvotes: 0

coder-at-risk
coder-at-risk

Reputation: 21

We can use the requestServerAuthCode method with the "WebApplication ClientID" and create a method to fetch the access token as below;

 new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)

                    .requestServerAuthCode("WEBAPPLICATION CLIENT ID")

                    .requestEmail()

                    .build())

As seen we need a WEBAPPLICATION CLIENT ID we can be obtained from 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();
            }
        }
    });
}

Please use compile 'com.squareup.okhttp:okhttp:2.6.0' (ver 3-RC1 will have different classes) or you can use any network framework to make the above call

With a successful response, you will have the following info in 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"**
     }

as it is seen the acces_token is available for further use.

Upvotes: 2

yubaraj poudel
yubaraj poudel

Reputation: 3879

In my case i had previously,

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

I fixed it by adding adding the requestToken method,

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

Now its working for me.Hopefully this can help somebody having issues like me.

Upvotes: 21

BNK
BNK

Reputation: 24114

As I have answered at the following question:

Google Sign-In requestIdToken returns null

In order to request Id Token sucessfully, you should use a "Web application" type Client Id, instead of "Android" type Client Id.

You also find at Google's documentation, the following info (please note #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.


Update Mar 26:

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

Upvotes: 51

Related Questions