Phone Authentication Using Firebase

Introduction

Phone authentication is one of the most commonly used authentication methods in mobile applications. It allows users to sign in or sign up using their mobile number, bypassing the need for email accounts or passwords. This method is especially popular in regions where users are more comfortable with mobile numbers than email addresses.

Firebase Authentication provides a robust and secure way to implement phone authentication in Flutter applications. It handles sending verification codes via SMS, verifying the code, and signing in users, reducing the complexity of building a secure authentication system from scratch.

This post covers a comprehensive guide on phone authentication in Flutter, including setup, implementation, handling verification codes, best practices, and common challenges.


How Phone Authentication Works

Phone authentication in Firebase follows a simple process:

  1. User Enters Phone Number: The user inputs their mobile number in the app.
  2. Firebase Sends Verification Code: Firebase sends a one-time SMS verification code to the provided number.
  3. User Enters Verification Code: The user enters the received code in the app.
  4. Firebase Verifies the Code: Firebase validates the code and authenticates the user.
  5. User Signed In: Upon successful verification, the user is signed in, and a Firebase user instance is created.

This process ensures secure authentication without requiring passwords, providing a user-friendly login experience.


Setting Up Firebase for Phone Authentication

Before implementing phone authentication in Flutter, Firebase must be properly set up.

Step 1: Add Firebase to Your Flutter Project

  1. Create a Firebase project in the Firebase Console.
  2. Add Android and iOS apps to the project.
  3. Download and configure google-services.json for Android and GoogleService-Info.plist for iOS.
  4. Add Firebase packages in pubspec.yaml:
dependencies:
  firebase_core: ^3.5.0
  firebase_auth: ^5.2.0
  1. Initialize Firebase in main.dart:
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Step 2: Enable Phone Authentication in Firebase Console

  1. Go to your Firebase project console.
  2. Navigate to Authentication → Sign-in Method.
  3. Enable Phone authentication.
  4. Optionally, configure phone number testing for development to avoid using real SMS.

Implementing Phone Authentication in Flutter

Phone authentication typically involves two main steps: sending the verification code and verifying the code.

Step 1: Send Verification Code

Use Firebase’s verifyPhoneNumber method to send the SMS code.

import 'package:firebase_auth/firebase_auth.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;

void sendVerificationCode(String phoneNumber) async {
  await _auth.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
  // Auto-retrieval or instant verification
  await _auth.signInWithCredential(credential);
},
verificationFailed: (FirebaseAuthException e) {
  // Handle error
  print('Verification failed: ${e.message}');
},
codeSent: (String verificationId, int? resendToken) {
  // Store verificationId for later use
  print('Code sent to $phoneNumber');
},
codeAutoRetrievalTimeout: (String verificationId) {
  // Auto-retrieval timeout
},
); }
  • verificationCompleted: Called when the phone number is automatically verified.
  • verificationFailed: Called when verification fails.
  • codeSent: Called when the verification code is successfully sent.
  • codeAutoRetrievalTimeout: Called when automatic code retrieval times out.

Step 2: Verify the SMS Code

After receiving the code, the user inputs it in the app, and it must be verified using the stored verificationId.

void verifyCode(String verificationId, String smsCode) async {
  PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: smsCode,
); try {
await _auth.signInWithCredential(credential);
print('Phone number verified and user signed in');
} catch (e) {
print('Failed to verify code: $e');
} }

Once the credential is validated, Firebase creates a user session, and the user is signed in.


Handling Automatic Verification

Firebase provides automatic verification on some devices, which allows the app to sign in the user without manually entering the SMS code. This feature is triggered in verificationCompleted callback and is particularly useful for enhancing the user experience.


Best Practices for Phone Authentication

  1. Use Firebase Test Phone Numbers
    Firebase allows using test numbers during development to avoid sending real SMS messages.
  2. Handle Errors Gracefully
    Common errors include invalid numbers, quota exceeded, or too many attempts. Display user-friendly messages for these scenarios.
  3. Implement Resend Option
    Allow users to request a new verification code if they do not receive the first one.
  4. Secure Verification Flow
    Ensure that verification IDs are stored securely and not exposed to potential attackers.
  5. Consider Regional Limitations
    Some regions may have delays or restrictions in SMS delivery. Implement timeouts and fallback mechanisms.

Common Challenges and Solutions

1. SMS Delays or Failures

  • Ensure the phone number is correctly formatted with the country code.
  • Use Firebase test numbers during development to avoid real SMS issues.

2. Handling Multiple Devices

  • Avoid storing verification IDs globally; store them per session.
  • Handle edge cases where the same number is used on multiple devices.

3. Automatic Verification Not Triggered

  • Automatic verification may not work on all devices.
  • Always provide a manual SMS code input as a fallback.

Integrating Phone Authentication with UI

Phone authentication typically requires two screens:

  1. Phone Number Input Screen
    • User enters their phone number.
    • App sends verification code using verifyPhoneNumber.
  2. Code Verification Screen
    • User enters the SMS code.
    • App verifies the code and signs in the user.

Example of a simple UI:

TextField(
  controller: phoneController,
  decoration: InputDecoration(labelText: 'Phone Number'),
),
ElevatedButton(
  onPressed: () => sendVerificationCode(phoneController.text),
  child: Text('Send Code'),
),
TextField(
  controller: codeController,
  decoration: InputDecoration(labelText: 'Verification Code'),
),
ElevatedButton(
  onPressed: () => verifyCode(storedVerificationId, codeController.text),
  child: Text('Verify Code'),
),

Advantages of Phone Authentication

  1. User-Friendly
    Many users prefer using their phone numbers instead of remembering passwords.
  2. No Passwords Required
    Reduces friction and risk of password-related security issues.
  3. Widely Adopted
    Especially popular in regions with limited email usage.
  4. Secure and Scalable
    Firebase handles SMS sending and verification securely.

Use Cases for Phone Authentication

  • Messaging apps like WhatsApp
  • E-commerce apps for quick sign-in
  • Fintech apps requiring secure user verification
  • Delivery apps targeting regions where email usage is low


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *