Table of Contents

    Book an Appointment

    What is the Context Behind This Firebase Custom Authentication Challenge?

    While working on a cross-platform SaaS platform designed for field service management, we encountered a fascinating identity management challenge. The application, built with Flutter, required three primary sign-in methods: Apple Sign-In, Google Sign-In and a custom email OTP flow. Because field workers often shared corporate devices or switched between iOS and Android, seamless cross-device login was a hard business requirement.

    Initially, the system was designed with a strict constraint: no dedicated backend or Cloud Functions. The custom email OTP flow was handled entirely on the client side. The app generated a 6-digit code, sent it via an SMTP service and authenticated the user against Firebase using a fixed derived password. However, we soon realized this architectural decision created a severe conflict when users attempted to cross over from Apple Sign-In to the OTP flow. This challenge required a deep dive into firebase custom authentication and ultimately inspired this article so other engineering teams can avoid the pitfalls of client-side identity orchestration.

    How Did the Identity Collision Occur in the Architecture?

    The core of the issue surfaced in the way Firebase handles identity providers and account linking. The business use case demanded that a user could create an account on their iPhone using Apple Sign-In and later log into an Android tablet using the custom email OTP flow with the exact same email address.

    To facilitate the OTP flow without a backend, the client app verified the SMTP-delivered code and then attempted to log the user in using a deterministic, derived password associated with their email. The logic looked something like this:

    try {
      cred = await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: derivedPassword,
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found' || e.code == 'invalid-credential') {
        cred = await FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: email,
          password: derivedPassword,
        );
      } else {
        rethrow;
      }
    }
    

    While this functioned in isolation, it completely fractured when interacting with accounts originally provisioned via OAuth providers. The Firebase Console was explicitly set to “Link accounts that use the same email,” yet the client-side implementation failed to honor this seamlessly.

    What Went Wrong with the Client-Side Authentication Flow?

    When a user who originally signed up with Apple on one device tried the email OTP flow on another device, the authentication pipeline collapsed under conflicting states.

    • The Read Failure: The signInWithEmailAndPassword method failed immediately with an invalid-credential error. Because the account was created via Apple, it had no associated password provider in Firebase.
    • The Write Failure: Falling back to createUserWithEmailAndPassword subsequently failed with an email-already-in-use error, locking the user out entirely.

    Compounding the issue, Firebase’s Email Enumeration Protection was enabled. This security feature prevents attackers from verifying whether an email exists in the system, but it also deprecates and obfuscates client-side methods like fetchSignInMethodsForEmail. Calling it would occasionally return the Apple provider, but often returned an empty array, making it completely unreliable for preemptive conflict detection.

    What Alternative Solutions Did We Consider?

    As we diagnosed the bottleneck, we evaluated multiple strategies to reconcile the identities. When companies hire software developer teams for complex architecture, evaluating tradeoffs before writing code is a crucial part of the delivery process.

    Can We Use Client-Side Credential Linking?

    We explored using currentUser.linkWithCredential(). This approach works flawlessly if a user is already signed in via Apple or Google and *then* links an email credential. However, it requires an active session. It provided zero utility for users trying to log in fresh on a new device using only their email.

    Can We Rely on Pre-Flight Sign-In Method Checks?

    We attempted to use fetchSignInMethodsForEmail(email) to detect the conflict upfront and route the user to the correct provider. However, with Email Enumeration Protection enabled (a mandatory security best practice), this method is effectively neutralized. Relying on it leads to inconsistent state management and unpredictable UI flows.

    Can We Maintain the “No Backend” Constraint?

    The initial requirement was to avoid backend infrastructure entirely. However, as senior architects, we had to address the elephant in the room: generating OTPs locally, sending them via client-side SMTP and authenticating via a fixed derived password is a critical security anti-pattern. If a malicious actor reverse-engineered the password derivation logic from the Flutter binary, they could bypass the OTP entirely and compromise any user account.

    Should We Adopt Server-Side Custom Tokens?

    We concluded that solving this purely from the client application was architecturally impossible without compromising security or user experience. The only resilient, secure and correct solution was to offload the OTP validation and identity linking to a lightweight backend service utilizing firebase custom token authentication.

    How Do You Implement Secure Firebase Custom Token Authentication?

    To permanently resolve the Apple Sign-In and OTP collision, we introduced a serverless function. This approach securely handles the SMTP dispatch, verifies the OTP and safely bridges the identity gap without relying on insecure client-side derived passwords.

    1. The Backend Implementation (Node.js)

    We deployed a lightweight Cloud Function. When the user submits their OTP, the client sends it to this secure endpoint. The backend verifies the OTP, checks if a Firebase user exists with that email, creates one if they don’t and mints a custom token.

    const admin = require('firebase-admin');
    admin.initializeApp();
    exports.verifyOtpAndMintToken = async (req, res) => {
      const { email, otp } = req.body;
      
      // 1. Verify OTP against your database/cache securely
      const isValidOtp = await verifySecureOtp(email, otp);
      if (!isValidOtp) {
        return res.status(401).send('Invalid OTP');
      }
      let userRecord;
      try {
        // 2. Look up the existing user (e.g., the Apple-created account)
        userRecord = await admin.auth().getUserByEmail(email);
      } catch (error) {
        if (error.code === 'auth/user-not-found') {
          // 3. Create user if they do not exist
          userRecord = await admin.auth().createUser({ email });
        } else {
          return res.status(500).send('Internal Server Error');
        }
      }
      // 4. Generate the custom token for the unified UID
      const customToken = await admin.auth().createCustomToken(userRecord.uid);
      return res.json({ token: customToken });
    };
    

    2. The Client-Side Implementation (Flutter)

    With the backend handling the security logic, the Flutter application’s responsibility is drastically simplified. We replaced the derived password hack with Firebase’s native custom token sign-in.

    Future<void> signInWithVerifiedOtp(String email, String otp) async {
      try {
        // 1. Send OTP to backend and receive custom token
        final response = await apiService.post('/verifyOtpAndMintToken', data: {
          'email': email,
          'otp': otp,
        });
        
        final String customToken = response.data['token'];
        // 2. Authenticate cleanly with Firebase Custom Authentication
        await FirebaseAuth.instance.signInWithCustomToken(customToken);
        
        // User is now authenticated under their unified UID, regardless of Apple/Google origins
      } catch (e) {
        // Handle error gracefully
      }
    }
    

    What Should Engineering Teams Take Away From This Authentication Challenge?

    When organizations hire backend developers for scalable architectures, they expect teams to look beyond the immediate code syntax and evaluate the broader security and system design implications. Here are the core lessons from this engagement:

    • Never Trust Client-Side Authentication Orchestration: Generating OTPs and maintaining derived passwords on the client is a severe vulnerability. Authentication state and secrets must live on a trusted server boundary.
    • Understand IAM and Provider Linking: Firebase account linking works best when orchestrated by the Admin SDK. The client SDK is deliberately restricted from manipulating existing provider credentials without explicit user re-authentication.
    • Embrace Serverless for Identity: Constraints like “no backend” are often well-intentioned to reduce overhead, but identity management requires secure environments. A simple serverless function provides massive security ROI.
    • Respect Security Features: Features like Email Enumeration Protection will break older client-side validation techniques (like `fetchSignInMethodsForEmail`). Modern architectures must account for privacy-first security postures.
    • Invest in Specialized Engineering: Authentication bugs can destroy user trust. When you hire app developer to create a mobile app, ensure the team possesses deep knowledge of the underlying IAM platforms, not just UI frameworks.

    How Can We Summarize This Firebase Architecture Lesson?

    By transitioning from a flawed client-side derived password model to a robust firebase custom token authentication architecture, we resolved the conflicting identity states between Apple Sign-In and custom email OTPs. We removed critical security vulnerabilities, honored Firebase’s enumeration protection and delivered a seamless cross-device experience for the end user. If your organization is facing complex authentication roadblocks or needs to modernize its cloud architecture, contact us to explore how our dedicated remote engineering teams can help.

    Social Hashtags

    #FirebaseAuthentication #FlutterDevelopment #FirebaseAuth #CustomTokenAuthentication #FlutterFirebase #FirebaseSecurity #AppleSignIn #EmailOTP #FirebaseCloudFunctions #MobileAppDevelopment #CrossPlatformDevelopment #BackendDevelopment #IdentityManagement #AppSecurity #ServerlessArchitecture

    Frequently Asked Questions