Firebase Authentication is a service that provides easy-to-use authentication methods for your applications. It supports various authentication mechanisms, including email and password, social media logins, and anonymous sign-ins. This module will introduce you to Firebase Authentication, its features, and how to integrate it into your application.

Key Concepts

  1. Authentication Methods:

    • Email and Password: Traditional method where users sign up with an email address and password.
    • Social Media Logins: Allows users to sign in using their social media accounts (e.g., Google, Facebook, Twitter).
    • Anonymous Authentication: Enables users to interact with your app without providing any credentials.
    • Phone Authentication: Users can sign in using their phone number and a verification code sent via SMS.
  2. Firebase Authentication SDK:

    • Provides a set of tools and libraries to implement authentication in your app.
    • Available for various platforms, including iOS, Android, and web.
  3. Firebase Console:

    • A web-based interface to manage authentication settings, view user data, and configure authentication providers.

Setting Up Firebase Authentication

Step 1: Create a Firebase Project

  1. Go to the Firebase Console.
  2. Click on "Add project" and follow the on-screen instructions to create a new project.

Step 2: Enable Authentication Providers

  1. In the Firebase Console, navigate to the "Authentication" section.
  2. Click on the "Sign-in method" tab.
  3. Enable the desired authentication providers (e.g., Email/Password, Google, Facebook).

Step 3: Add Firebase to Your App

For Web

  1. Add Firebase SDK to your project by including the following script tags in your HTML file:

    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js"></script>
    
  2. Initialize Firebase in your JavaScript file:

    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
    import { getAuth } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js";
    
    // Your web app's Firebase configuration
    const firebaseConfig = {
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
        projectId: "YOUR_PROJECT_ID",
        storageBucket: "YOUR_PROJECT_ID.appspot.com",
        messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
        appId: "YOUR_APP_ID"
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    

For Android

  1. Add the Firebase SDK to your build.gradle file:

    dependencies {
        implementation 'com.google.firebase:firebase-auth:21.0.1'
    }
    
  2. Initialize Firebase in your MainActivity.java:

    import com.google.firebase.auth.FirebaseAuth;
    
    public class MainActivity extends AppCompatActivity {
        private FirebaseAuth mAuth;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Initialize Firebase Auth
            mAuth = FirebaseAuth.getInstance();
        }
    }
    

Practical Example: Email and Password Authentication

Sign Up

import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js";

const auth = getAuth();
const email = "[email protected]";
const password = "userpassword";

createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
        // Signed in 
        const user = userCredential.user;
        console.log("User signed up:", user);
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.error("Error signing up:", errorCode, errorMessage);
    });

Sign In

import { getAuth, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js";

const auth = getAuth();
const email = "[email protected]";
const password = "userpassword";

signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
        // Signed in 
        const user = userCredential.user;
        console.log("User signed in:", user);
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.error("Error signing in:", errorCode, errorMessage);
    });

Practical Exercise

Task

  1. Set up a Firebase project and enable Email/Password authentication.
  2. Create a simple web page with a sign-up form and a sign-in form.
  3. Implement the sign-up and sign-in functionality using Firebase Authentication.

Solution

  1. Follow the steps in the "Setting Up Firebase Authentication" section to create a Firebase project and enable Email/Password authentication.

  2. Create an HTML file with the following content:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Firebase Authentication</title>
        <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js"></script>
        <script>
            // Your web app's Firebase configuration
            const firebaseConfig = {
                apiKey: "YOUR_API_KEY",
                authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
                projectId: "YOUR_PROJECT_ID",
                storageBucket: "YOUR_PROJECT_ID.appspot.com",
                messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
                appId: "YOUR_APP_ID"
            };
    
            // Initialize Firebase
            const app = firebase.initializeApp(firebaseConfig);
            const auth = firebase.auth();
    
            function signUp() {
                const email = document.getElementById("signUpEmail").value;
                const password = document.getElementById("signUpPassword").value;
                auth.createUserWithEmailAndPassword(email, password)
                    .then((userCredential) => {
                        const user = userCredential.user;
                        console.log("User signed up:", user);
                    })
                    .catch((error) => {
                        console.error("Error signing up:", error.code, error.message);
                    });
            }
    
            function signIn() {
                const email = document.getElementById("signInEmail").value;
                const password = document.getElementById("signInPassword").value;
                auth.signInWithEmailAndPassword(email, password)
                    .then((userCredential) => {
                        const user = userCredential.user;
                        console.log("User signed in:", user);
                    })
                    .catch((error) => {
                        console.error("Error signing in:", error.code, error.message);
                    });
            }
        </script>
    </head>
    <body>
        <h1>Firebase Authentication</h1>
        <h2>Sign Up</h2>
        <input type="email" id="signUpEmail" placeholder="Email">
        <input type="password" id="signUpPassword" placeholder="Password">
        <button onclick="signUp()">Sign Up</button>
    
        <h2>Sign In</h2>
        <input type="email" id="signInEmail" placeholder="Email">
        <input type="password" id="signInPassword" placeholder="Password">
        <button onclick="signIn()">Sign In</button>
    </body>
    </html>
    

Summary

In this section, you learned about Firebase Authentication and its various methods. You also set up Firebase Authentication in your project and implemented basic email and password authentication. In the next section, we will dive deeper into email and password authentication, including password reset and email verification.

© Copyright 2024. All rights reserved