Authenticate Using Google Sign-In on Android with Firebase

Authentication is a key step in developing Android applications. There are several approaches to do authentication. Letting users authenticate with Firebase using their Google Accounts by integrating Google Sign-in to our applications is one approach. Other than using Google Sign-in, Firebase facilitates to sign in using Email-Password, Facebook, Twitter, Github and by Phone.

In here I will explain on how to authenticate using Google Sign-in. There are few steps to follow.

  • Device with Android 4.0 (Ice Cream Sandwich) or above.
  • Google Play Services from the Google Repository Available in the Android SDK Manager.
  • Android studio 1.5 or higher.

Android Studio latest version ( 2.2 or above) provide inbuilt support for Firebase. It has Firebase assistant which is really helpful to connect our apps with Firebase and install necessary Gradle dependencies. Let’s start from the begining and will first create the android project. Steps followed are shown in the following figures.




After creating the project, to start the Firebase assistant.

  • click Tools -> Firebase. It will open up the assistant window. As I’m currently explaining about Authentication I will select Authentication option from the given functionalities.
  • As you can see the steps to follow in that window are given step by step.
  • Now click on Connect to Firebase button and it will open up another window. From there whether you want to create a new Firebase project to connect this app or you want to select an existing project to connect this app(Single Firebase project can have multiple apps connected. You need not to create a Firebase project each time when you create a app).
  • After selecting the option click on Connect to Firebase button. It will connect your app to Firebase.
  • Then click on Add Firebase Authentication to your app button to add the given code to your app.

Now the app has been successfully connected with Firebase.

compile 'com.google.firebase:firebase-auth:11.0.4'
compile 'com.google.android.gms:play-services-auth:11.0.4'
  • Login to Firebase console and select your project from it. Clicking on the project will show you the apps that you have connected. On the left side there is a menu. Select Authentication from it. Then you will be asked to set up a sign-in method. Select Google from it and make it Enabled and Save it.

Authenticating with Firebase

This is the original tutorial on how to integrate Google Sign-in to your app.

  • Call requestIdToken in GoogleSignInOptions.
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

You must pass the clientID to the requestIdToken method. To find the client ID navigate to here

  1. After integrating with Google Sign-in our code will have something like this.
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}

@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 {
// Google Sign In failed, update UI appropriately
// ...
}
}
}

2. In your sign-in activity’s onCreate method, get the shared instance of the FirebaseAuth object:

private FirebaseAuth mAuth;
// ...
mAuth = FirebaseAuth.getInstance();

3. When initializing your Activity, check to see if the user is currently signed in:

@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}

4. After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}

// ...
}
});
}

If the call to signInWithCredential succeeds you can use the getCurrentUser method to get the user's account data.

5. To sign out a user

FirebaseAuth.getInstance().signOut();

Source Code is available here

Comments