5 – Phone Number Authentication with Firebase

Phone Number Authentication with Firebase

Phone number authentication is a popular and secure method to verify user identities in your mobile or web applications. Firebase offers a convenient way to implement phone number authentication in your project. In this guide, we’ll explore how to set up and use phone number authentication with Firebase, complete with examples and best practices.

1. Prerequisites

Before you begin implementing phone number authentication, make sure you have the following prerequisites in place:

  • Firebase Project: Create a Firebase project or use an existing one on the Firebase Console (https://console.firebase.google.com/).
  • Development Environment: Set up your development environment for your target platform, such as Android Studio for Android, Xcode for iOS, or a text editor for web development.
2. Enabling Phone Number Sign-In

First, enable phone number sign-in methods for your Firebase project:

  1. Go to the Firebase Console and select your project.
  2. In the left menu, navigate to “Authentication.”
  3. Click on the “Sign-in method” tab.
  4. Enable the “Phone” sign-in provider.
3. Implementing Phone Number Authentication

Now, let’s implement phone number authentication in your application. Below are platform-specific examples:

For Web (HTML/JavaScript)

If you’re developing a web application, you can use the Firebase JavaScript SDK to implement phone number authentication. Here’s an example:


// Initialize Firebase
var config = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
};

firebase.initializeApp(config);

// Phone Number Authentication
var phoneNumber = "+1 555-555-5555";
var appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
    .then((confirmationResult) => {
        // SMS sent to the user
        var code = prompt("Enter the verification code sent to your phone:");
        return confirmationResult.confirm(code);
    })
    .then((result) => {
        // User is authenticated
        var user = result.user;
    })
    .catch((error) => {
        // Handle authentication error
        console.error(error);
    });

This code initializes phone number authentication, sends an SMS with a verification code, and confirms the user’s identity.

For Android

If you’re developing an Android application, you can use the Firebase Authentication SDK to implement phone number authentication. Here’s an example:


// Initialize Firebase
String apiKey = "YOUR_API_KEY";

PhoneAuthProvider.getInstance().verifyPhoneNumber(
        "+1 555-555-5555",        // Phone number to verify
        60,                       // Timeout duration
        TimeUnit.SECONDS,          // Unit of timeout
        this,                     // Activity (for callback binding)
        new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onCodeSent(String verificationId,
                                   PhoneAuthProvider.ForceResendingToken token) {
                // SMS sent to the user
            }

            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential) {
                // User is authenticated
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                // Handle verification error
                Log.e(TAG, "onVerificationFailed", e);
            }
        });

This code initializes phone number verification, sends an SMS with a verification code, and confirms the user’s identity.

For iOS

If you’re developing an iOS application, you can use the Firebase Authentication SDK to implement phone number authentication. Here’s an example:


// Initialize Firebase
let verificationID: String? = nil
let phoneNumber = "+1 555-555-5555"

PhoneAuthProvider.provider()
    .verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationID, error in
        if let error = error {
            // Handle verification error
            print("Error: \(error.localizedDescription)")
            return
        }

        // SMS sent to the user
        self.verificationID = verificationID
    }

// To confirm the verification code
let verificationCode = "123456" // Enter the received code here
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)

Auth.auth().signIn(with: credential) { authResult, error in
    if let error = error {
        // Handle authentication error
        print("Error: \(error.localizedDescription)")
        return
    }

    // User is authenticated
    if let user = authResult?.user {
        print("User: \(user.uid)")
    }
}

This code initiates phone number verification, sends an SMS with a verification code, and confirms the user’s identity.

4. Security and Privacy

When implementing phone number authentication, ensure that you handle user data securely and protect user privacy. Follow these best practices:

  • Permissions: Request only the necessary permissions when users provide their phone numbers and respect their privacy preferences.
  • Data Protection: Safeguard user data and ensure compliance with data protection regulations, such as GDPR.
5. Testing and Deployment

Before deploying your application, thoroughly test the phone number authentication feature to ensure it works as expected. Test the verification and authentication flows on different devices and networks.

Once testing is complete, you can deploy your application to your chosen platform, whether it’s the web, Android, or iOS.

Conclusion

Implementing phone number authentication with Firebase is a secure and convenient way to verify user identities in your applications. By following the steps and best practices outlined in this guide, you can provide a seamless phone number authentication experience for your app’s users.