Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Firebase Authentication Tutorial

Introduction

Firebase Authentication provides backend services to help you authenticate users in your application. It supports email and password login, social media logins, and more. This tutorial will guide you through integrating Firebase Authentication into an Android application.

Setup Firebase Project

First, you need to create a Firebase project and add your Android app to it.

  1. Go to the Firebase Console and click on "Add project".
  2. Follow the steps to create a new Firebase project.
  3. After creating the project, click on the "Add App" button and select Android.
  4. Register your app with the package name and follow the instructions to download the google-services.json file.
  5. Add the google-services.json file to the app directory of your Android project.
  6. Add the following dependencies to your build.gradle files:

Project-level build.gradle:

buildscript {
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

App-level build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // Add this line

dependencies {
    // Add this line
    implementation 'com.google.firebase:firebase-auth:21.0.1'
}

Initialize Firebase in Android

Next, initialize Firebase in your application. Open your MainActivity.java file and initialize Firebase in the onCreate() method.

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.FirebaseApp;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Firebase
        FirebaseApp.initializeApp(this);
    }
}

Email and Password Authentication

Firebase Authentication supports various methods, but we'll start with email and password authentication.

Sign Up

Create a new user with an email and password:

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;

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

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

    private void createAccount(String email, String password) {
        mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    FirebaseUser user = mAuth.getCurrentUser();
                } else {
                    // If sign in fails, display a message to the user.
                }
            });
    }
}

Sign In

Authenticate a user with an email and password:

private void signIn(String email, String password) {
    mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                FirebaseUser user = mAuth.getCurrentUser();
            } else {
                // If sign in fails, display a message to the user.
            }
        });
}

Google Sign-In

Firebase Authentication can easily integrate with Google Sign-In.

Configure Google Sign-In

First, configure your app to use Google Sign-In by following these steps:

  1. Go to the Firebase Console and navigate to the Authentication section.
  2. Enable Google Sign-In under the Sign-In Method tab.
  3. In your Android project, add the Google Sign-In dependency:
implementation 'com.google.android.gms:play-services-auth:19.2.0'

Integrate Google Sign-In

Now, integrate Google Sign-In in your MainActivity.java:

import com.google.android.gms.auth.api.Auth;
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.firebase.auth.AuthCredential;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity {
    private static final int RC_SIGN_IN = 9001;
    private GoogleSignInClient mGoogleSignInClient;
    private FirebaseAuth mAuth;

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

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

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        mAuth = FirebaseAuth.getInstance();
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        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) {
            Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    FirebaseUser user = mAuth.getCurrentUser();
                } else {
                    // If sign in fails, display a message to the user.
                }
            });
    }
}

Conclusion

In this tutorial, we covered the basics of integrating Firebase Authentication into an Android application. We walked through setting up a Firebase project, initializing Firebase in Android, and implementing email/password and Google sign-in methods. Firebase Authentication supports various other authentication methods, such as Facebook, Twitter, and GitHub, which can be easily integrated using similar steps.