Showing posts with label firebase authentication. Show all posts

Firebase Google plus Authentication in Android

As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase in android. In this article, we will how to perform Google Plus authentication in Android.

You can find my previous posts from following,

  1. Firebase Email Authentication

  2. Firebase Phone Authentication

Firebase G-Plus Authentication:

Firebase facilities Developers to manage Google plus Authentication in Easy way. Before starting, we have add or enable Google plus Authentication in Firebase console.

Firebase Setup:

Before start coding, we have to setup firebase for android and enable Phone Authentication. If you are new to firebase, the following link will be useful to know the method for setting up the project in firebase.

After setting up, open Authentication sign in method and enable phone authentication method as shown in the following figure.

You should Add SHA Fingerprint in your application. The following terminal will be used to get the SHA Fingerprint with Command Prompt in Windows for debug mode.

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.

Step 1: Creating New Project with Empty Activity.

Step 2: Setting up the Firebase Library.

Step 3: Implementation of Firebase Google Plus Authentication.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and select your activity template.


  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Firebase Library

In this part, we will see how to setup the library for the project.

  1. Open your project level build.gradle file and add the following lines in dependencies.

    dependencies {
        …
        classpath 'com.google.gms:google-services:4.0.1'
        …
    }
  2. Then add the following lines in allprojects in project level build.gradle file.

    allprojects {
        repositories {
            google()
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    }
  3. Then add the following lines in app level build.gradle file to apply google services to your project.

    dependencies {
        ...
        implementation 'com.google.firebase:firebase-auth:16.0.2'
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.squareup.picasso:picasso:2.71828'
    }
    apply plugin: 'com.google.gms.google-services'
  4. Then click “Sync Now” to setup your project.

Step 3: Implementation of Firebase Google plus Authentication:

Initialize Google Sign in Client with Google Sign in options and Firebase Auth Client like shown in below snippet.

//first we initialized the Firebase Auth object
FirebaseAuth mAuth = FirebaseAuth.getInstance();

//Then we need a GoogleSignInOptions object
//And we need to build it as below
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  .requestIdToken(getString(R.string.default_web_client_id))
  .requestEmail()
  .build();

//Then we will get the GoogleSignInClient object from GoogleSignIn class
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID: Open the Credentials page in the API Console. The Web application type client ID is your backend server's OAuth 2.0 client ID.

Then add the following code to initiate Google sign in.

//getting the google signin intent
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
//starting the activity for result
startActivityForResult(signInIntent, RC_SIGN_IN);

Add the onActivityResult as shown below

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

 //if the requestCode is the Google Sign In code that we defined at starting
 if (requestCode == RC_SIGN_IN) {

  //Getting the GoogleSignIn Task
  Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
  try {
   //Google Sign In was successful, authenticate with Firebase
   GoogleSignInAccount account = task.getResult(ApiException.class);
   //authenticating with firebase
   firebaseAuthWithGoogle(account);
  } catch (ApiException e) {
   Log.v("API Exception", e.toString());
   Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
  }
 }
}

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

 //getting the auth credential
 AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

 //Now using firebase we are signing in the user here
 mAuth.signInWithCredential(credential)
                            .addOnCompleteListener(this, new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    if (mAuth.getCurrentUser() != null) {
     startActivity(new Intent(LoginActivity.this, MainActivity.class));
     finish();
    }
   } else {
    // If sign in fails, display a message to the user.
    Log.w(TAG, "signInWithCredential:failure", task.getException());
    Toast.makeText(LoginActivity.this, "Authentication failed.",
     Toast.LENGTH_SHORT).show();
   }
  }
 });
}

If the user is authenticated with Google Plus Sign In successfully, then login screen is redirected to the next activity.

To retrieve user details like name, profile picture, mail id through Firebase, use the following snippets.

FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();

assert user != null;
textName.setText(user.getDisplayName());
textEmail.setText(user.getEmail());

Picasso.get().load(user.getPhotoUrl()).into(imageView);

Here, I have used Picasso Image Loading Library to load images. To more click here.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.