Android Firebase Authentication for Google Signin fails

Dinuka Jay

I followed the firebase documentation from top to bottom and implemented a simple google Sign in option to my app. However, when I try to signin, the process halts after selecting a google account and results in an error inside the onActivityResult method:

if (requestCode == RC_SIGN_IN) {
       GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
       if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
       } else {
            //THE CODE BREAKS HERE
            // Google Sign In failed, update UI appropriately
       }
}

The code breaks at the if (result.isSuccess()) condition. To elaborate further, here's the complete code I implemented after going through the doc:

onCreate:

public class TestLogin extends AppCompatActivity {

    private SignInButton mGoogleBtn;
    private static int RC_SIGN_IN = 226;
    private GoogleApiClient mGoogleApiClient;
    private  String TAG = "Checkmate";
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_login);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null){
                    //success
                }
            }
        };

        mGoogleBtn = (SignInButton) findViewById(R.id.googleBtn);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("MY_CLIENT_ID-MY_CLIENT_ID.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        //Failed
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        mGoogleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                statusMessage.setText("Loading..");
                signIn();
            }
        });
    }

signIn method:

The SignIn method gets called when the Google Signin button is clicked:

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

onActivityResult:

onActivityResult is called when the result is received after clicking the button. This is where the error occurs:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                //THE CODE BREAKS HERE
                // Google Sign In failed, update UI appropriately
            }
        }
    }

Handling Firebase Login code for Google:

This method never gets called because the code breaks at the onActivityResult condition.

    private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        
                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Toast.makeText(TestLogin.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

Checklist:

Yes, I added the google_services.json file to the /app directory

Yes, I created a new OAuth Client Key in the Google Credentials page

Here's my gradle:

dependencies {
    compile 'com.google.android.gms:play-services:9.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.google.firebase:firebase-storage:9.6.1'
}
apply plugin: 'com.google.gms.google-services'

And..

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}
hmaxf2

In my previous test app using Firebase FriendlyChat, I have encountered similar failure in Sign In, but I have solved it by going Google API console (https://console.developers.google.com/apis/credentials?project=) then download "client_secret.json" (in my case, I need to rename the downloaded filename "client_secret_xxxxx.json") for your Android client, put this file in your AndroidStudio project under "/src/main/resources" (create "resources" folder if not exist) then try to compile and run your Android app again.

Summary: you need 2 json files : "google-services.json" from Firebase Console and "client_secret.json" from Google API Console.

Hope this solve your problem.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

android - Firebase Google Authentication user not logging out

分類Dev

Google signin in Android app to consume Cloud Endpoints backend

分類Dev

How to migrate asp.net core authentication to new Google SignIn service?

分類Dev

How to resolve issue of "com.google.android.gms.auth.api.signin.internal.SignInHubActivity" ActivityNotFoundException in google signin integration

分類Dev

Firebase iOS SDK authentication with private Google storage

分類Dev

How to set the callbacks for Android Firebase Phone Authentication?

分類Dev

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/auth/api/signin/internal/zzz;

分類Dev

Firebase admin how to create user with passwordless signin?

分類Dev

Manifest merger Failed after adding Google Firebase Authentication

分類Dev

重複エントリ:com / google / android / gms / auth / api / signin / internal / zzf.class

分類Dev

How to change the Signed in Phone Number in Firebase Authentication for Android?

分類Dev

ADFS 2.0 single sign out fails after multiple signin and signout

分類Dev

Authentication failed on the server. Google maps api. Android

分類Dev

In-app purchases (IAP) in android with BOTH Google and Facebook authentication?

分類Dev

nullオブジェクト参照の「android.content.Intentcom.google.android.gms.auth.api.signin.GoogleSignInClient.getSignInIntent()」

分類Dev

Firebase and new Google Sign-In on Android

分類Dev

when new user create it signIn automatically in firebase in javascript

分類Dev

Does Firebase Auth (JS) support offline signin attempts?

分類Dev

JWT Authentication fails in Hyperledger Composer

分類Dev

Firebase Authentication & React

分類Dev

Firebase authentication is not working as intended

分類Dev

java.lang.NoClassDefFoundError:解決に失敗しました:Lcom / google / android / gms / auth / api / signin / internal / zzz;

分類Dev

複数のdexファイルがLcom / google / android / gms / auth / api / signin / zzcを定義します。

分類Dev

react-native-google-signinおよびandroid.support.v4.netが存在しませんエラー

分類Dev

react-native-google-signinおよびandroid.support.v4.netが存在しませんエラー

分類Dev

Google SignIn validation error using jwt-go

分類Dev

ポッド「Google / SignIn」とポッド「GoogleSignIn」

分類Dev

Google+ SDK for iOS Add Signin button programmatically

分類Dev

Google signIn tokenId が invalid_token です

Related 関連記事

  1. 1

    android - Firebase Google Authentication user not logging out

  2. 2

    Google signin in Android app to consume Cloud Endpoints backend

  3. 3

    How to migrate asp.net core authentication to new Google SignIn service?

  4. 4

    How to resolve issue of "com.google.android.gms.auth.api.signin.internal.SignInHubActivity" ActivityNotFoundException in google signin integration

  5. 5

    Firebase iOS SDK authentication with private Google storage

  6. 6

    How to set the callbacks for Android Firebase Phone Authentication?

  7. 7

    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/auth/api/signin/internal/zzz;

  8. 8

    Firebase admin how to create user with passwordless signin?

  9. 9

    Manifest merger Failed after adding Google Firebase Authentication

  10. 10

    重複エントリ:com / google / android / gms / auth / api / signin / internal / zzf.class

  11. 11

    How to change the Signed in Phone Number in Firebase Authentication for Android?

  12. 12

    ADFS 2.0 single sign out fails after multiple signin and signout

  13. 13

    Authentication failed on the server. Google maps api. Android

  14. 14

    In-app purchases (IAP) in android with BOTH Google and Facebook authentication?

  15. 15

    nullオブジェクト参照の「android.content.Intentcom.google.android.gms.auth.api.signin.GoogleSignInClient.getSignInIntent()」

  16. 16

    Firebase and new Google Sign-In on Android

  17. 17

    when new user create it signIn automatically in firebase in javascript

  18. 18

    Does Firebase Auth (JS) support offline signin attempts?

  19. 19

    JWT Authentication fails in Hyperledger Composer

  20. 20

    Firebase Authentication & React

  21. 21

    Firebase authentication is not working as intended

  22. 22

    java.lang.NoClassDefFoundError:解決に失敗しました:Lcom / google / android / gms / auth / api / signin / internal / zzz;

  23. 23

    複数のdexファイルがLcom / google / android / gms / auth / api / signin / zzcを定義します。

  24. 24

    react-native-google-signinおよびandroid.support.v4.netが存在しませんエラー

  25. 25

    react-native-google-signinおよびandroid.support.v4.netが存在しませんエラー

  26. 26

    Google SignIn validation error using jwt-go

  27. 27

    ポッド「Google / SignIn」とポッド「GoogleSignIn」

  28. 28

    Google+ SDK for iOS Add Signin button programmatically

  29. 29

    Google signIn tokenId が invalid_token です

ホットタグ

アーカイブ