Tag

firebase authentication

Browsing

In this blog, I’m going to show you adding Google Sign In using firebase in your android app. It very easy to do just follow below step. So let’s get started.

Step of Implementation Google Authentication
  • Create an android project
  • Setup and add project on firebase console.
  • Enable Google Sign In
  • Add SHA and 256 keys to the app on firebase console. (Required step for Google Sign In )
  • Add authentication library in app-level build.gradle
  • Setup Google client
1. Create an android project

Let’s move to android studio and create a new project. In this sample application, I’m taking a package name is com.googlesigninfirebase for demonstration of Google Sign in using firebase. let’s go to next step.

2. Setup new firebase project on firebase console.

Let’s open the firebase console and add a project. For adding a project on firebase follow my previous post. Adding Firebase to Android App Manually

3. Enable Google Sign In

Select Authentication from the left panel. Go to the Sign In method and you can select Google and enable the Google SignIn. In sort ( Authentication -> Sign In Method -> Google -> Enable ).

4. Add SHA and 256 keys to the app on firebase console

This is the required step for google sign In. Now go to the android studio project. To get the signature of the app clicks the gradle on right-hand side. Now select app -> task -> android and select singingReport.

You just need to copy and paste in project setting in firebase. You have to set both keys SHA1 and SHA-256. Now come back to android studio follow next step.

Add authentication library in app-level build.gradle
 implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
 // Google Sign In SDK (only required for Google Sign In)
 implementation 'com.google.android.gms:play-services-auth:17.0.0'
Create a new activity along with layout named is LoginActivity

Open layout file and button for demonstration

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    >

  <com.google.android.gms.common.SignInButton
      android:id="@+id/sign_in_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="8dp"
      android:layout_marginTop="8dp"
      android:layout_marginEnd="8dp"
      android:layout_marginBottom="8dp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />

</androidx.constraintlayout.widget.ConstraintLayout>
Open LoginActvitiy and paste following code
package com.googlesigninfirebase;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class LoginActivity extends AppCompatActivity {
  private static final String TAG = "LoginActivity";
  private static final int RC_SIGN_IN = 1001;

  GoogleSignInClient googleSignInClient;

  private FirebaseAuth firebaseAuth;

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

    SignInButton signInButton = findViewById(R.id.sign_in_button);
    signInButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        // Launch Sign In
        signInToGoogle();
      }
    });

    // Configure Google Client
    configureGoogleClient();
  }

  private void configureGoogleClient() {
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        // for the requestIdToken, this is in the values.xml file that
        // is generated from your google-services.json 
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

    // Build a GoogleSignInClient with the options specified by gso.
    googleSignInClient = GoogleSignIn.getClient(this, gso);

    // Set the dimensions of the sign-in button.
    SignInButton signInButton = findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_WIDE);

    // Initialize Firebase Auth
    firebaseAuth = FirebaseAuth.getInstance();
  }

  @Override
  public void onStart() {
    super.onStart();

    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = firebaseAuth.getCurrentUser();

    if (currentUser != null) {
      Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());
      showToastMessage("Currently Logged in: " + currentUser.getEmail());
    }
  }

  public void signInToGoogle() {
    Intent signInIntent = googleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
      Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
      try {
        // Google Sign In was successful, authenticate with Firebase
        GoogleSignInAccount account = task.getResult(ApiException.class);
        showToastMessage("Google Sign in Succeeded");
        firebaseAuthWithGoogle(account);
      } catch (ApiException e) {
        // Google Sign In failed, update UI appropriately
        Log.w(TAG, "Google sign in failed", e);
        showToastMessage("Google Sign in Failed " + e);
      }
    }
  }

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

    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    firebaseAuth.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
              FirebaseUser user = firebaseAuth.getCurrentUser();

              Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());

              showToastMessage("Firebase Authentication Succeeded ");
              launchMainActivity(user);
            } else {
              // If sign in fails, display a message to the user.

              Log.w(TAG, "signInWithCredential:failure", task.getException());

              showToastMessage("Firebase Authentication failed:" + task.getException());
            }
          }
        });
  }

  private void showToastMessage(String message) {
    Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
  }

  private void launchMainActivity(FirebaseUser user) {
    if (user != null) {
      MainActivity.startActivity(this, user.getDisplayName());
      finish();
    }
  }
}
Open MainActvity layout add logout and revoke access button
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >


  <Button
      android:id="@+id/buttonLogout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:text="@string/logout"
      android:textAllCaps="false"
      app:layout_constraintBottom_toTopOf="@+id/buttonDisconnect"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
  <Button
      android:id="@+id/buttonDisconnect"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/revoke_access"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />
  <TextView
      android:id="@+id/textViewWelcome"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginBottom="32dp"
      android:text="@string/welcome"
      android:gravity="center"
      app:layout_constraintBottom_toTopOf="@+id/buttonLogout"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>

Go to main activity and add logout code

package com.googlesigninfirebase;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  private static final String TAG = "MainActivity";
  private static final String ARG_NAME = "username";

  public static void startActivity(Context context, String username) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra(ARG_NAME, username);
    context.startActivity(intent);
  }

  FirebaseAuth firebaseAuth;
  GoogleSignInClient googleSignInClient;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = findViewById(R.id.textViewWelcome);
    if (getIntent().hasExtra(ARG_NAME)) {
      textView.setText(String.format("Welcome - %s", getIntent().getStringExtra(ARG_NAME)));
    }
    findViewById(R.id.buttonLogout).setOnClickListener(this);
    findViewById(R.id.buttonDisconnect).setOnClickListener(this);

    googleSignInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_SIGN_IN);
    firebaseAuth = FirebaseAuth.getInstance();
  }

  @Override
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.buttonLogout:
        signOut();
        break;
      case R.id.buttonDisconnect:
        revokeAccess();
        break;
    }
  }

  private void signOut() {
    // Firebase sign out
    firebaseAuth.signOut();

    // Google sign out
    googleSignInClient.signOut().addOnCompleteListener(this,
        new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Signed out of google");
          }
        });
  }

  private void revokeAccess() {
    // Firebase sign out
    firebaseAuth.signOut();

    // Google revoke access
    googleSignInClient.revokeAccess().addOnCompleteListener(this,
        new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Revoked Access");
          }
        });
  }
}

Conclusion

With the help of this android app tutorial, We have learned Google Sign In using Firebase android. I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Welcome guys, In this post I’ll show you sign in with email with FirebaseUI. Firebase provides many ways for authentication. Here, I’ll explain FirebaseUI to login using email and password. so Let’s get started.

Why should use FirebaseUI for Authentication?

FirebaseUI is an open-source library, you can also customize it because of open source. It eliminates boilerplate code and promotes android best practices with user experiences and security. FirebaseUI is all enabled single tap to enable and returning users also.

Connect your app to firebase

Let’s open an android studio and create a new android project with the empty activity template. I’m taking the package name here com.firebaseauthenticationuiexample . Once the project created, connect your app to the firebase. Please follow this article for creating a project on firebase console.

Add a new classpath in project-level build.gradle

Open the project-level build.gradle and add the below line.

//Add this line
classpath 'com.google.gms:google-services:4.3.2'
Add new plugin in app-level build.gradle

Open the app-level build.gradle and google services plugin by adding this line

// add this line
apply plugin: 'com.google.gms.google-services'
Add firebase UI auth dependency in same app level gradle file

Firebase UI auth library needs to perform a firebase auth with email.

implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

After adding sync the project and make sure everything is working fine.

Enable email and password authentication on firebase console.

Go to the firebase console and enable email password authentication. So go to the Authentication option in the left panel. Once you open on authentication go to Sign In method and enable email password.

firebase login with email and password android
Create a LoginActvitiy

I’m creating a new activity with a layout file. Here I’m adding a button for initiating login just for demonstration purposes. Let’s go to the layout file and add SignIn button just like below

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    >
  <Button
      android:id="@+id/buttonSignIn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="SignIn with Email"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />

</androidx.constraintlayout.widget.ConstraintLayout>
Let’s go to LoginActivity.

In the LoginActivity, before initiating sign-in make sure your user is already login for not in previous session. you can check something like this.

    FirebaseAuth auth = FirebaseAuth.getInstance();
    if (auth.getCurrentUser() != null) {
      // already signed in
    } else {
      // not signed in 
    }

Create and launch sign-in intent

If the user is not signed-in then by the initiated sign-in process by creating auth intent. This you can specify service URL and include the link inside, or customized theme as well. You need to create and launch sign-in intent just like this.

    // Choose authentication providers
    List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.EmailBuilder().build());

    // Create and launch sign-in intent
    startActivityForResult(
        AuthUI.getInstance()
            .createSignInIntentBuilder()
            .setAvailableProviders(providers)
            .build(),
        RC_SIGN_IN);

Check Response code on Activity Result

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // RC_SIGN_IN is the request code you passed into
    if (requestCode == 1234) {

      // Successfully signed in
      if (resultCode == RESULT_OK) {
        // Successfully signed in
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        Toast.makeText(getApplicationContext(), "Successfully signed in", Toast.LENGTH_SHORT)
            .show();
        launchMainActivity(user);
      }
    } else {
      // Sign in failed. If response is null the user canceled the sign-in flow using the back button. Otherwise check
      // response.getError().getErrorCode() and handle the error.
      Toast.makeText(getApplicationContext(), "Unable to Sign in", Toast.LENGTH_SHORT).show();
    }
  }
Finally, the login activity source code look like this.
package com.firebaseauthenticationuiexample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
import java.util.List;

public class LoginActivity extends AppCompatActivity {
  private static final int RC_SIGN_IN = 1234;

  public static void startActivity(Context context) {
    Intent intent = new Intent(context, LoginActivity.class);
    context.startActivity(intent);
  }

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

    // find view
    Button buttonSignIn = findViewById(R.id.buttonSignIn);
    // Set onclick listener
    buttonSignIn.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {
          Toast.makeText(getApplicationContext(), "User already signed in, must sign out first",
              Toast.LENGTH_SHORT).show();
          // already signed in
        } else {
          // Choose authentication providers
          List<AuthUI.IdpConfig> providers = Arrays.asList(
              new AuthUI.IdpConfig.EmailBuilder().build());

          // Create and launch sign-in intent
          startActivityForResult(
              AuthUI.getInstance()
                  .createSignInIntentBuilder()
                  .setAvailableProviders(providers)
                  .build(),
              RC_SIGN_IN);
        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // RC_SIGN_IN is the request code you passed into
    if (requestCode == 1234) {

      // Successfully signed in
      if (resultCode == RESULT_OK) {
        // Successfully signed in
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        Toast.makeText(getApplicationContext(), "Successfully signed in", Toast.LENGTH_SHORT)
            .show();
        launchMainActivity(user);
      }
    } else {
      // Sign in failed. If response is null the user canceled the sign-in flow using the back button. Otherwise check
      // response.getError().getErrorCode() and handle the error.
      Toast.makeText(getApplicationContext(), "Unable to Sign in", Toast.LENGTH_SHORT).show();
    }
  }

  private void launchMainActivity(FirebaseUser user) {
    if (user != null) {
      MainActivity.startActivity(this, user.getDisplayName());
      finish();
    }
  }
}
Implement logout in MainActivity

Your login stuff is done. Now I’m going to explain the logout part. open the main activity layout file add one button for perform logout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

  <Button
      android:id="@+id/buttonLogout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Logout"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"

      />
  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:text="Welcome"
      android:textColor="@color/colorAccent"
      android:textSize="20sp"
      app:layout_constraintBottom_toTopOf="@+id/buttonLogout"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>
Let’s open the main activity source file

Doing signout firebase auth provider gives callback onComplete methods. just like below.

package com.firebaseauthenticationuiexample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity {
  private static final String ARG_NAME = "username";

  public static void startActivity(Context context, String username) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra(ARG_NAME, username);
    context.startActivity(intent);
  }

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

    TextView textView = findViewById(R.id.textView);
    if (getIntent().hasExtra(ARG_NAME)) {
      textView.setText(String.format("Welcome - %s", getIntent().getStringExtra(ARG_NAME)));
    }

    Button logout = findViewById(R.id.buttonLogout);
    logout.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        AuthUI.getInstance()
            .signOut(MainActivity.this)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
              public void onComplete(@NonNull Task<Void> task) {
                // user is now signed out
                Toast.makeText(getApplicationContext(), "User has signed out!", Toast.LENGTH_SHORT)
                    .show();
                launchLoginActivity();
              }
            });
      }
    });
  }

  private void launchLoginActivity() {
    LoginActivity.startActivity(MainActivity.this);
    finish();
  }
}

With the help of this android app tutorial, We have learned firebaseui for authentication with email I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Keep in touch

If you want to keep in touch and get an email when I write new blog posts, follow me on facebook or subscribe usIt only takes about 10 seconds to register. 

Still, if you have any queries please put your comment below.