Firebase Authentication provides backend services to developers out there, in order to authenticate users in the application. As we know every app needs to identify the user first and then to show resources like data and other information (Authentication is simply the SignIn process for the apps). In this tutorial, we will implement the Firebase Authentication Android Implementation service provided by Firebase using Google sign-in.
Steps to create and connect the new Firebase project to the Android application.
1. Create a Firebase developer account at https://firebase.google.com/ and click on ‘GO TO CONSOLE’.
2. Click on “Add project”.
3. Fill in the project name and click on continue.
4. Enable Google Analytics and click “Continue”.
5. Choose Google Analytics account and click “Create Project”.
6. When your new project is successfully created click on “Continue”.
7. Now select “Android”.
8. Connect your app to Firebase by providing required app information and click on “Register app”.
You can get the app certificate SHA-1 key through the following steps:
- Open Android project.
- Click on Gradle tab from a right-side panel.
- Open app-> task-> android-> signingReport.
- You will find your app SHA-1 key on ‘Gradle Console’.
9. Now download the ‘google-services.json’ file to add it into the Android application and click on “Next”.
You can add “google-services.json” to your app through the following steps:
- Open Android Studio.
- Switch to project view from the left side panel.
- Copy and paste “google-services.json” in the app directory.
10. Click on “Next” again and then click “Continue to console”.
11. In the console page select Authentication -> Sign-in method -> Google -> Enable and click on “Save”.
Add the following dependencies to your Android app.
build.gradle(Project)
1 2 3 4 5 6 7 |
repositories { mavenCentral() } dependencies { classpath "com.android.tools.build:gradle:4.1.3" classpath "com.google.gms:google-services:4.3.5" } |
build.gradle (Module)
AndroidManifest.xml
Add the Internet permission in the AndroidManifest.xml file to access the network connection.
1 |
<uses-permission android:name="android.permission.INTERNET" /> |
Android Firebase Authentication with Google Sign-In Example
In this example, we will implement Firebase Authentication Android Implementation in our Android app.
Once the user successfully Sign-In through Google then we will authenticate the user with
Firebase Authentication and will navigate the user to Profile Activity.
We will display the user details in Profile Activity.
activity_main.xml
Add the following code in acitivity_main.xml. We will implement the Google Sign-In button in this acivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?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" android:padding="5dp" tools:context=".MainActivity"> <com.google.android.gms.common.SignInButton android:id="@+id/btnGoogleSignIn" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
MainActivity.java
Add the following code in MainActivity.java class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class MainActivity extends AppCompatActivity { public static final String TAG = "GoogleSignIn"; public static final int RC_SIGN_IN = 321; private SignInButton btnSignInWithGoogle; private GoogleSignInClient mGoogleSignInClient; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSignInWithGoogle = findViewById(R.id.btnGoogleSignIn); mAuth = FirebaseAuth.getInstance(); requestGoogleSignIn(); btnSignInWithGoogle.setOnClickListener(view -> { signIn(); }); } } |
Create a method called requestGoogleSignIn in MainActivity.java outside the onCreate()
method and put in the below codes. Call this method in the onCreate() method.
1 2 3 4 5 6 7 8 9 |
private void requestGoogleSignIn(){ // Configure sign-in to request the user’s basic profile like name and email GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso); } |
Create a method signIn() that will be called when the Sign In Button is clicked in the view,
this will prompt the user to select a Google account before the authentication process begins.
this method will handle sign-in by creating a sign-in intent with the getSignInIntent() method,
and starting the intent with startActivityForResult().
1 2 3 4 |
private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } |
we will authenticate the user by creating a new method firebaseAuthWithGoogle(String idToken)
with a string parameter. In this method, we will get user credentials when the user selects google Gmail to SignIn with.
We will call this method in our onActivityResult().
Put in the below codes in the firebaseAuthWithGoogle(String idToken) method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
private void firebaseAuthWithGoogle(String idToken) { //getting user credentials with the help of AuthCredential method and also passing user Token Id. AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); //trying to sign in user using signInWithCredential and passing above credentials of user. mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); // Sign in success, navigate user to Profile Activity Intent intent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intent); } else { // If sign in fails, display a message to the user. Toast.makeText(MainActivity.this, "User authentication failed", Toast.LENGTH_SHORT).show(); } } }); } |
Now override onActivityResult() method in MainActivity.java. In this method, we will check if the requestCode is
equal to our defined RC_SIGN_IN code then we will get public information of the user, as a result, eg Name,
Email, and PhotoUrl and we will also get a Token Id so after getting this information we will call our
firebaseAuthWithGoogle() method and will pass received Token id.
After all this, we will need to put user information in SharedPreferences to access it ProfileActivity
later when the user is signed in.
Add the below code in your onActivityResult() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
@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) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); //authenticating user with firebase using received token id firebaseAuthWithGoogle(account.getIdToken()); //assigning user information to variables String userName = account.getDisplayName(); String userEmail = account.getEmail(); String userPhoto = account.getPhotoUrl().toString(); userPhoto = userPhoto+"?type=large"; //create sharedPreference to store user data when user signs in successfully SharedPreferences.Editor editor = getApplicationContext() .getSharedPreferences("MyPrefs",MODE_PRIVATE) .edit(); editor.putString("username", userName); editor.putString("useremail", userEmail); editor.putString("userPhoto", userPhoto); editor.apply(); Log.i(TAG, "onActivityResult: Success"); } catch (ApiException e) { Log.e(TAG, "onActivityResult: " + e.getMessage()); } } } |
The last we need to do that will check if the user leaves the app and come back to the app and the
user is previously signed in then we will navigate the user to ProfileActivity.java.
To do so override the onStart() method in MainActivity.java and add the below code in onStart().
1 2 3 4 5 6 7 8 |
@Override protected void onStart() { super.onStart(); FirebaseUser user = mAuth.getCurrentUser(); if (user != null){ startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } } |
So the code for MainActivity.java is completed.
Complete code of MainActivity.java
profile_activity.xml
Add the following code in the profile_activity.xml file. In this activity, we will show the user name,
user email, and user photo so we have 2 TextViews, 1 ImageView, and a Button to Sign-out user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?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=".ProfileActivity"> <ImageView android:id="@+id/userImage" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginTop="32dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:srcCompat="@tools:sample/avatars" /> <TextView android:id="@+id/userName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" tools:text="Username" android:textSize="28sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/userImage" /> <TextView android:id="@+id/userEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" tools:text="Email" android:textSize="28sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/userName" /> <Button android:id="@+id/btnLogout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="32dp" android:text="Sign Out" android:textAllCaps="false" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
ProfileActivity.java
In ProfileActivity.java we will get stored information of the user from SharedPreferences and display
all the information in the created views in activity_profile.xml.
We will sign-out user using FirebaseAuth.getInstance.signOut() and navigate the user back to
MainActivity.java once the user clicks on the Sign Out button.
And we will load Image from URL using Glide library.
Below is the code for ProfileActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; public class ProfileActivity extends AppCompatActivity { public static final String TAG = "GoogleSignIn"; TextView tvUserName; TextView tvUserEmail; ImageView userImageView; Button btnSignOut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); tvUserName = findViewById(R.id.userName); tvUserEmail = findViewById(R.id.userEmail); userImageView = findViewById(R.id.userImage); btnSignOut = findViewById(R.id.btnLogout); SharedPreferences preferences = this.getSharedPreferences("MyPrefs", MODE_PRIVATE); String userName = preferences.getString("username",""); String userEmail = preferences.getString("useremail", ""); String userImageUrl = preferences.getString("userPhoto",""); tvUserName.setText(userName); tvUserEmail.setText(userEmail); Glide.with(this).load(userImageUrl).into(userImageView); btnSignOut.setOnClickListener(view -> { FirebaseAuth.getInstance().signOut(); goToMainActivity(); }); } private void goToMainActivity() { startActivity(new Intent(ProfileActivity.this, MainActivity.class)); } } |