Search code examples
flutterfirebasefirebase-authenticationfirebase-admin

firebase_auth/custom-token-mismatch The custom token corresponds to a different audience


I have a Flutter application in production with many users, using Firebase Backend. I want to add Firebase authentication to it by generating a custom token via a google cloud function.

I created another Firebase project as a dev environment and implemented and tested Firebase auth via a NodeJS cloud function, everything is great, and now I deployed the cloud function to the production environment.

I don't use any API Google API keys in NodeJS since all cloud functions are authenticated automatically on GCP. In Flutter, I replaced the dev environment google-services.json with the correct one in production. I don't have any GoogleService-Info, I'm testing on Android.

In main.dart, I initialize my app like this

  if (Firebase.apps.isEmpty) {
    try {
      await Firebase.initializeApp(
        name: "foo",
        options: DefaultFirebaseOptions.currentPlatform,
      );
    } catch (e) {
      print("could not initialize firebase ${e}");
    }
  }

options: DefaultFirebaseOptions.currentPlatform, is a file generated by FlutterFire CLI, it contains, the production app credentials, this is the only file I forgot to change when I was doing the dev environment testing, I forgot to create new apps for development and change the values in firebase_options.dart

Now what's happening is, the cloud function is generating the token correctly but whenever I try to sign in via this token in Flutter

await FirebaseAuth.instance.signInWithCustomToken(firebase_token);

I get this error

flutter (14645): Authentication error [firebase_auth/custom-token- 
mismatch] The custom token corresponds to a different audience.

How to fix this error? I can't just create new Firebase apps, if that's the root cause of the error, for two reasons

  1. I can't delete the existing because existing users won't be able to use the application

  2. I can't create new apps, because the Android package name is required, which is used by the existing apps.

So I want a solution that doesn't require disturbing existing users, if possible.


Solution

  • Issue solved by running Flutter clean, and Flutter pub get.

    It turns out that Flutter caches The Google service account between builds. Uninstalling the app and clearing the cache of the app, doesn't help, it's Flutter that's caching the file on the PC.

    I'm answering my own question rather than deleting this post because this answer might help future users. The other answers on this topic say to create a new app or create a new key or whatever.

    If you face this error, and nothing works for you, then just clear the cache on your PC.