Popular Searches
Popular Course Categories
Popular Courses

Implementing User Authentication with Firebase Authentication

Implementing User Authentication with Firebase Authentication

Firebase Integration and Cloud Services

Implementing User Authentication with Firebase Authentication

Course: iOS App Development

Topic: Implementing User Authentication with Firebase Authentication

Course Link: iOS App Development Training

Demo Link: Register for a Course Demo

Academy Website: JustAcademy


1. Introduction to Firebase Authentication

Firebase Authentication is a service that helps developers verify user identities and manage sign-in workflows in iOS applications. It provides ready-made authentication APIs so developers can implement account registration, login, logout, password recovery, and supported identity-provider sign-in without building an entire authentication backend from scratch.

Firebase Authentication can be integrated into Swift applications built with SwiftUI or UIKit. After a user signs in successfully, the app can display personalized information and request access to resources protected by appropriate security rules.

Authentication and authorization are different. Authentication verifies who a user is, while authorization determines which information and actions that user is permitted to access. Hiding a screen is not sufficient to protect private data; permissions must also be enforced by database rules or trusted backend services.

Learning Objectives

  • Understand authentication and authorization in iOS applications.
  • Create and configure a Firebase project.
  • Install and initialize the Firebase SDK.
  • Implement email-and-password registration and login.
  • Observe authentication state and update the user interface.
  • Implement sign-out and password-reset functionality.
  • Handle authentication errors and protect private data.
  • Test authentication workflows using development tools.

2. What Is User Authentication?

User authentication is the process of verifying a person's identity before allowing access to an account or service. Depending on the application's requirements, authentication may use a password, email link, phone verification, or a configured third-party identity provider.

Concept Meaning Example
Authentication Verifies the user's identity. Signing in with an email and password.
Authorization Controls access to resources. Allowing a user to read only their own profile.
Authentication state Represents whether a user is signed in. Displaying a home screen for an authenticated user.
Identity provider Provides a supported method of verifying identity. Google, Apple, or email/password sign-in.
Firebase UID A unique identifier for a Firebase Authentication user. Associating a profile document with its owner.

3. Features of Firebase Authentication

  • Email and password: Register and authenticate users with email addresses and passwords.
  • Email-link authentication: Allow users to sign in using a configured email link.
  • Phone authentication: Verify users through a supported phone and SMS workflow.
  • Federated sign-in: Integrate supported identity providers such as Google and Apple after completing their configuration.
  • Anonymous authentication: Create a temporary user identity that can potentially be linked to a permanent sign-in method.
  • Password recovery: Send password-reset emails for supported accounts.
  • User management: Access available profile information and manage authentication state through Firebase APIs.

The available methods depend on the providers enabled in Firebase Console and any additional configuration required by the chosen provider.

4. Authentication Workflow

  1. The user opens the iOS application.
  2. The application observes the current Firebase authentication state.
  3. A signed-out user sees the login or registration screen.
  4. The user enters credentials and submits the form.
  5. The application validates basic input and sends the request to Firebase Authentication.
  6. Firebase returns a successful result or an error.
  7. The interface updates based on the resulting authentication state.
  8. The authenticated user requests protected resources through services that enforce access permissions.

5. Prerequisites

  • A compatible version of Xcode.
  • Basic knowledge of Swift and SwiftUI or UIKit.
  • An iOS project with a known bundle identifier.
  • A Firebase project.
  • The Firebase SDK installed in the project.
  • An enabled authentication provider, such as Email/Password.
  • Internet access for Firebase authentication requests.

6. Create and Configure a Firebase Project

  1. Open the Firebase Console.
  2. Create a new Firebase project or select an existing project.
  3. Add an iOS application to the Firebase project.
  4. Enter the bundle identifier exactly as it appears in Xcode.
  5. Download the GoogleService-Info.plist configuration file.
  6. Add the file to the Xcode project and ensure it is included in the application target.
  7. Open Authentication in Firebase Console.
  8. Enable Email/Password under the available sign-in methods.
  9. Confirm that the app uses the intended Firebase project and configuration.

Important: The registered bundle identifier must match the one configured in Xcode. A mismatch may prevent the app from using the expected Firebase configuration.

7. Install the Firebase SDK

Firebase supports Swift Package Manager for adding its SDK to Apple-platform applications.

  1. Open the project in Xcode.
  2. Select File > Add Package Dependencies.
  3. Enter the repository URL https://github.com/firebase/firebase-ios-sdk.
  4. Select a package version compatible with the application.
  5. Add the FirebaseAuth product to the app target.
  6. Add FirebaseCore if required by the project's initialization setup.
  7. Allow Xcode to resolve and download the dependencies.

Check the official Firebase installation instructions for the SDK version used by your project. Firebase Authentication setup guide.

8. Initialize Firebase in a SwiftUI Application

Firebase should be configured before its authentication APIs are used. A SwiftUI app can initialize Firebase in its entry point.

import SwiftUI
import FirebaseCore

@main
struct AuthenticationDemoApp: App {
    init() {
        FirebaseApp.configure()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

For UIKit applications, Firebase is commonly initialized during application startup through the app delegate. Configure Firebase once rather than repeatedly inside individual views.

9. Import Firebase Authentication

Files that use Firebase Authentication APIs need to import the authentication module.

import FirebaseAuth

The expression Auth.auth() provides access to the configured Firebase Authentication instance.

10. Create a User Account

Firebase provides createUser(withEmail:password:completion:) for creating an email-and-password account. The following example returns either a Firebase user or an error.

import FirebaseAuth

func registerUser(
    email: String,
    password: String,
    completion: @escaping (Result<User, Error>) -> Void
) {
    Auth.auth().createUser(withEmail: email, password: password) { result, error in
        if let error = error {
            completion(.failure(error))
            return
        }

        guard let user = result?.user else {
            let error = NSError(
                domain: "Authentication",
                code: -1,
                userInfo: [
                    NSLocalizedDescriptionKey: "Unable to create the account."
                ]
            )
            completion(.failure(error))
            return
        }

        completion(.success(user))
    }
}

How Registration Works

  • The function receives the email address and password.
  • Firebase attempts to create the account.
  • If the operation fails, the error is returned to the caller.
  • If the operation succeeds, the Firebase user object is returned.
  • The calling view can display confirmation and update the interface.

Do not show a success message until Firebase confirms the operation. If email verification is part of the workflow, send a verification email and determine which features require a verified address.

11. Sign In with Email and Password

Firebase provides signIn(withEmail:password:completion:) to authenticate an existing user.

import FirebaseAuth

func signInUser(
    email: String,
    password: String,
    completion: @escaping (Result<User, Error>) -> Void
) {
    Auth.auth().signIn(withEmail: email, password: password) { result, error in
        if let error = error {
            completion(.failure(error))
            return
        }

        guard let user = result?.user else {
            let error = NSError(
                domain: "Authentication",
                code: -2,
                userInfo: [
                    NSLocalizedDescriptionKey: "Unable to sign in."
                ]
            )
            completion(.failure(error))
            return
        }

        completion(.success(user))
    }
}

When sign-in succeeds, Firebase updates its authentication state. The application should respond to that state instead of relying only on a manually set Boolean variable.

12. Observe Authentication State Changes

An application should react to changes in authentication state, including sign-in, sign-out, and session restoration. Firebase provides an authentication state listener for this purpose.

import FirebaseAuth
import Combine

final class AuthStateManager: ObservableObject {
    @Published var currentUser: User?

    private var authListener: AuthStateDidChangeListenerHandle?

    init() {
        authListener = Auth.auth().addStateDidChangeListener { [weak self] _, user in
            DispatchQueue.main.async {
                self?.currentUser = user
            }
        }
    }

    deinit {
        if let authListener {
            Auth.auth().removeStateDidChangeListener(authListener)
        }
    }
}

Explanation

  • ObservableObject makes the manager observable by compatible SwiftUI views.
  • @Published announces changes to the current user.
  • addStateDidChangeListener observes Firebase authentication changes.
  • The current user is updated when the listener reports a change.
  • The listener is removed when the manager is deallocated.

This example uses the Combine-based ObservableObject approach. Newer SwiftUI projects may use the Observation framework. The important principle is to maintain one reliable source of authentication state.

13. Display Screens Based on Authentication State

A SwiftUI application can display different views depending on whether a Firebase user is signed in.

import SwiftUI
import FirebaseAuth

struct ContentView: View {
    @StateObject private var authManager = AuthStateManager()

    var body: some View {
        Group {
            if let user = authManager.currentUser {
                VStack(spacing: 16) {
                    Text("Welcome")
                        .font(.title)

                    Text(user.email ?? "Signed-in user")

                    Button("Sign Out") {
                        do {
                            try Auth.auth().signOut()
                        } catch {
                            print("Sign-out failed")
                        }
                    }
                }
            } else {
                Text("Please sign in to continue.")
            }
        }
        .padding()
    }
}

This is a simplified demonstration. A complete app should show a dedicated login and registration interface when signed out, and a home screen when signed in. Production interfaces should display useful error messages rather than relying on console output.

14. Implement User Sign-Out

Sign-out ends the current Firebase Authentication session for the app. Firebase's sign-out method can throw an error, so handle the operation carefully.

import FirebaseAuth

func signOutUser() throws {
    try Auth.auth().signOut()
}

Call this function from the sign-out button. If the operation fails, show an understandable message. The authentication state listener should update the interface when Firebase reports the signed-out state.

15. Implement Password Reset

Firebase provides sendPasswordReset(withEmail:completion:) to request a password-reset email.

import FirebaseAuth

func sendPasswordReset(
    email: String,
    completion: @escaping (Result<Void, Error>) -> Void
) {
    Auth.auth().sendPasswordReset(withEmail: email) { error in
        if let error = error {
            completion(.failure(error))
        } else {
            completion(.success(()))
        }
    }
}

After a successful request, tell the user to check their email. Use privacy-conscious messaging that does not unnecessarily reveal whether an account exists. Firebase project settings and email-enumeration protection may affect the errors returned by authentication methods.

16. Validate User Input

Input validation helps users correct mistakes before a request is sent. Client-side validation improves usability, but Firebase must still enforce authentication and password requirements.

Validation Purpose Example
Email required Prevents empty submissions. Ask the user to enter an email address.
Email format Catches common typing mistakes. Check for a plausible email format.
Password required Prevents incomplete requests. Display a required-field message.
Password confirmation Reduces registration mistakes. Ensure both password fields match.
Loading state Prevents repeated requests. Disable the submit button during processing.

Configure the password policy in Firebase Console and explain the requirements to users. Avoid implementing local password rules that contradict the project's configured policy.

17. Handle Authentication Errors

Authentication can fail because of invalid credentials, connectivity problems, password-policy violations, account restrictions, rate limits, or incorrect project configuration.

Problem Possible Cause Recommended Solution
Registration fails Invalid email, password-policy violation, or existing account. Display a suitable message and let the user correct the input.
Login fails Incorrect credentials or account restrictions. Offer another attempt or password recovery.
Network failure Device is offline or the connection is unstable. Explain that the request could not complete and offer retry.
Too many requests Rate limits or abuse-prevention controls were triggered. Ask the user to wait before retrying.
Firebase initialization fails Missing configuration file or incorrect project setup. Check the bundle identifier, configuration file, and SDK initialization.
Password reset fails Invalid input, connectivity, or configuration issue. Show a clear recovery message and allow another attempt.

For production applications, map Firebase errors to appropriate user-facing messages. Avoid exposing internal diagnostics or sensitive information. Log only appropriate information for troubleshooting.

18. Manage User Profile Data

Firebase Authentication stores identity-related information such as a user's UID and available profile details. An application may need additional data, including display names, preferences, or profile settings. This information can be stored in Cloud Firestore or another suitable data store.

Use the Firebase UID as the stable identifier for a user's profile record. Avoid relying on an email address as the primary identifier because email addresses can change.

// Example Cloud Firestore structure:
//
// users/{firebaseUser.uid}
//
// Example fields:
// displayName: "Sample User"
// preferredLanguage: "en"
// createdAt: server-generated timestamp

This is an example data structure, not a complete database write operation. Configure Firestore Security Rules so users can access only the documents they are authorized to access.

19. Secure Private Data

Hiding a screen from signed-out users is not sufficient to protect data. A malicious client may attempt to access a database or API directly. Access permissions must be enforced by Firebase Security Rules or trusted backend services.

  • Use the Firebase UID to associate records with the correct account.
  • Write database rules that verify the authenticated identity and permitted actions.
  • Do not trust client-provided role names or permission flags.
  • When calling your own backend, send a Firebase ID token and verify it on the server.
  • Do not treat a UID alone as proof that a request is authenticated.
  • Test access rules with authorized and unauthorized users.

20. Security Best Practices

  • Never store passwords in plain text. Let Firebase Authentication manage credentials.
  • Keep private server credentials out of the app. An iOS application bundle cannot safely hide privileged secrets.
  • Use Security Rules. Protect Firestore, Realtime Database, and Cloud Storage independently of the UI.
  • Enable email verification where appropriate. Require verified email ownership for features that depend on it.
  • Consider multi-factor authentication. Use it where stronger account protection is appropriate and supported.
  • Protect sensitive logs. Never log passwords, authentication tokens, or unnecessary personal information.
  • Use secure transport. Avoid sending credentials through insecure custom network connections.
  • Prevent repeated submissions. Disable form buttons while requests are processing.
  • Review provider configuration. Confirm sign-in settings and authorized domains before release.
  • Test failure scenarios. Include offline behavior, invalid input, session changes, and unauthorized data access.

21. Common Implementation Mistakes

Mistake Why It Is a Problem Solution
Firebase is not initialized Authentication calls may fail because the SDK was not configured. Configure Firebase once during application startup.
Incorrect bundle identifier The app does not match its Firebase registration. Compare identifiers in Xcode and Firebase Console.
Authentication provider is disabled Firebase cannot process the selected sign-in method. Enable the correct provider in project settings.
Authentication state is hardcoded The interface may not match the real session state. Observe Firebase authentication state.
Errors are ignored Users cannot understand or recover from failures. Handle errors and provide clear feedback.
Only the interface is protected Private resources may still be accessible directly. Enforce authorization with Security Rules and backend checks.
Passwords are stored insecurely Credentials may be exposed. Let Firebase manage credentials and never save passwords in UserDefaults.

22. Testing Firebase Authentication

Test authentication flows using dedicated development accounts. Firebase's Local Emulator Suite can help test supported authentication workflows without depending entirely on production accounts.

  • Register a new account with valid details.
  • Attempt registration with missing or invalid input.
  • Sign in with correct and incorrect credentials.
  • Sign out and confirm that the signed-out interface appears.
  • Restart the app and check that authentication state is handled correctly.
  • Request a password-reset email.
  • Test offline behavior and network failures.
  • Verify that a user cannot read another user's private records.
  • Test email verification if the app requires it.
  • Test account deletion and reauthentication requirements if those features are supported.

23. Practical Project: Firebase Login and Registration App

Project Objective: Build an iOS application that lets users create accounts, sign in, access a home screen, reset a forgotten password, and sign out.

Suggested Screens

  1. Welcome Screen: Provides login and registration options.
  2. Registration Screen: Collects email, password, and password confirmation.
  3. Login Screen: Collects credentials and displays useful error messages.
  4. Password Recovery Screen: Requests a reset email.
  5. Home Screen: Displays available information about the signed-in user.
  6. Account Screen: Provides sign-out and account-management actions.

Development Checklist

  • Create and configure the Firebase project.
  • Add the Firebase SDK and initialize Firebase.
  • Enable Email/Password authentication.
  • Implement registration and sign-in functions.
  • Add password-reset and sign-out functionality.
  • Observe authentication state to choose the appropriate screen.
  • Add loading indicators and accessible error messages.
  • Protect user records with suitable Security Rules.
  • Test successful and unsuccessful authentication flows.
  • Document setup steps without committing private credentials.

24. Interview Questions and Answers

Q1. What is Firebase Authentication?

Firebase Authentication is a service that manages user identity and provides APIs for supported sign-in methods, including email/password and federated identity providers.

Q2. What is the difference between authentication and authorization?

Authentication verifies who the user is. Authorization determines which resources and actions the user is permitted to access.

Q3. How do you create an account with Firebase?

Use Auth.auth().createUser(withEmail:password:completion:) and handle both the error and successful user result.

Q4. How do you sign in an existing user?

Use Auth.auth().signIn(withEmail:password:completion:) and update the interface based on the authentication result and observed state.

Q5. What is a Firebase UID?

A Firebase UID is a unique identifier for a user within the Firebase project. It is commonly used to associate the user with profile data.

Q6. How can an app detect sign-in and sign-out?

Register an authentication state listener and update the app's observable state when Firebase reports a change.

Q7. How does password reset work?

The app calls Firebase's password-reset API with the user's email address. Firebase processes the request and sends a reset email when appropriate.

Q8. Is hiding a screen enough to secure private data?

No. Database Security Rules and trusted backend authorization must enforce access restrictions independently of the user interface.

Q9. Why should passwords not be stored in UserDefaults?

UserDefaults is not designed for storing passwords. Firebase should manage authentication credentials rather than the application saving passwords itself.

Q10. How can Firebase Authentication be tested safely?

Use a development Firebase project and, where appropriate, the Local Emulator Suite. Test valid and invalid credentials, network failures, session changes, and data-access restrictions.

25. Quick Revision Checklist

  • Firebase Authentication manages identity and supported sign-in workflows.
  • Register the iOS app using the correct bundle identifier.
  • Install the Firebase SDK and configure Firebase once.
  • Enable the authentication provider used by the application.
  • Use Firebase APIs for account creation, login, password recovery, and logout.
  • Observe authentication state instead of manually assuming a user is signed in.
  • Use the Firebase UID to associate profile data with a user.
  • Protect private data using Security Rules and trusted backend authorization.
  • Handle errors clearly and test successful and unsuccessful flows.
  • Never store passwords in plain text or expose authentication tokens in logs.

26. Official Learning Resources

Conclusion

Firebase Authentication simplifies the implementation of user registration and sign-in in iOS applications. By integrating the Firebase SDK, configuring authentication providers, observing user state, handling errors, and protecting private data with proper authorization rules, developers can build a more reliable authentication experience.

A well-designed authentication system combines a clear user interface with secure configuration, privacy-conscious error handling, server-enforced access control, and thorough testing.

Explore the iOS course: iOS App Development Training

Register for a demo: Book a Course Demo

Visit JustAcademy: JustAcademy Official Website

Previous Next
whatsapp