Skip to content

feat(core): add token providers for Auth, App Check and Messaging - #19009

Draft
jonathanedey wants to merge 6 commits into
feat/firebase-commonfrom
jedey/core/token-registry
Draft

jonathanedey wants to merge 6 commits into
feat/firebase-commonfrom
jedey/core/token-registry

Conversation

@jonathanedey

Copy link
Copy Markdown
Contributor

Description

Dart-only Firebase packages (firebase_ai, firebase_data_connect, pure-Dart cloud_functions) attach Auth, App Check, and FCM tokens to their own requests. Today they get them by hard-depending on firebase_auth, firebase_app_check, and firebase_messaging, so every app links all three and their versions move in lock-step.

This adds a small registry to firebase_core. Three contracts (AuthTokenProvider, AppCheckTokenProvider, MessagingTokenProvider) live in firebase_core_interface; each plugin registers an implementation per app at startup (dartPluginClass registrant on native, registerWith on web); consumers call app.getService<T>(). firebase_core's public API is unchanged. Consumers migrate in follow-up PRs.

Change highlights:

  • Registration happens before main, so a user restored from a previous launch gets a token on cold start. App Check answers the placeholder plus a reason before activate(), matching native Functions.
  • Error contracts differ on purpose: Auth throws, App Check returns placeholder plus reason, Messaging returns null. Each matches its native shape; the doc comments say why.
  • FCM read never prompts. Cached-only on Apple. Android has no non-registering read, so it uses getToken(), as native Functions does. Web reads only when permission is already granted. Default app only.
  • firebase_app_check_web behavior change: all delegates of an app now share one activated JS instance. Needed so the provider sees the app's activation; a second activate() is a no-op.

All three providers ship in the same firebase_core major so an old plugin can never resolve against a new consumer and silently drop a header.

Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • My PR includes unit or integration tests for all changed/updated/fixed behaviors (See Contributor Guide).
  • All existing and new tests are passing.
  • I updated/added relevant documentation (doc comments with ///).
  • The analyzer (melos run analyze) does not report any problems on my PR.
  • I read and followed the Flutter Style Guide.
  • I signed the CLA.
  • I am willing to follow-up on review comments in a timely manner.

Breaking Change

  • Yes, this is a breaking change.
  • No, this is not a breaking change.

Firebase packages that attach Auth, App Check and FCM tokens to their
own requests, as the Functions SDKs do, can ask the app for them through
AuthTokenProvider, AppCheckTokenProvider and MessagingTokenProvider
instead of depending on the packages that implement them. The
implementing packages register a provider, and
registerFirebaseServiceFactory lets them do so before any app exists, so
a provider is reachable before the app has used the package (for example
for a user restored from a previous launch). The contracts are
re-exported by firebase_core_platform_interface only, like the other
plugin contracts: the public API of firebase_core is unchanged.
firebase_auth and firebase_app_check register an AuthTokenProvider and
an AppCheckTokenProvider for every app before main, through a
dartPluginClass registrant on Android, Apple platforms and Windows, and
their web packages do so in registerWith. Other Firebase packages can
then get the ID token of a user restored from a previous launch, or an
App Check token, before the app has used FirebaseAuth or
FirebaseAppCheck itself. A failed App Check request, including one made
before the app activates App Check, answers with the placeholder token
of the SDKs and the reason, as the native interop APIs do. On web, every
App Check delegate of an app now shares the activated JS instance of the
app, so the provider sees the activation the app did through
FirebaseAppCheck.
firebase_messaging registers a MessagingTokenProvider for every app
before main through a dartPluginClass registrant on Android and Apple
platforms, and firebase_messaging_web does so in registerWith, so other
Firebase packages can attach the FCM registration token to their own
requests, as the Functions SDKs do. The provider reads the token through
the new FirebaseMessagingPlatform.getCachedToken rather than getToken,
so it never requests notification permission, and answers null when
there is no token or the read fails. Apple platforms read the token the
SDK holds; the Android token read returns the stored token and registers
one only when none is stored, as the Instance ID read the native
Functions SDK uses does; web reads it only once notification permission
is already granted, as the JS Functions SDK does. Messaging serves the
default app only, so the provider answers null for any other app.
The tests app links the Auth, App Check and Messaging plugins: each
provider is registered before the suite touches its plugin; the Auth
provider answers null when signed out and the ID token of the user
signed in against the emulator; the App Check provider answers with the
placeholder and the reason before activation and stays the same
provider once the app uses App Check; the Messaging provider answers
null or the token the SDK holds without prompting for permission.
@jonathanedey jonathanedey changed the title Jedey/core/token registry feat(core): add token providers for Auth, App Check and Messaging Nov 24, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces interop token providers (AuthTokenProvider, AppCheckTokenProvider, and MessagingTokenProvider) across the Firebase Flutter plugins, enabling packages to securely share authentication, App Check, and FCM registration tokens without direct dependencies. The changes span multiple packages, registering these providers before main on native platforms and web. The review feedback highlights three key areas for improvement: resolving a potential runtime TypeError in MethodChannelFirebaseMessaging.getCachedToken by allowing nullable values in invokeMapMethod, optimizing FirebaseMessagingWebTokenProvider to use the cached platform instance instead of instantiating a new class on every request, and wrapping the _delegate access in FirebaseMessagingWeb.getCachedToken within a try-catch block to safely handle initialization errors.

Comment on lines +375 to +378
Map<String, String?>? data = await channel
.invokeMapMethod<String, String>('Messaging#getCachedToken', {
'appName': app.name,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using invokeMapMethod<String, String> will cause a runtime TypeError if the returned map contains a null value (which happens when no FCM token is cached and the native side returns null). Since the variable data is typed as Map<String, String?>?, you should use invokeMapMethod<String, String?> to safely allow nullable values at runtime.

Suggested change
Map<String, String?>? data = await channel
.invokeMapMethod<String, String>('Messaging#getCachedToken', {
'appName': app.name,
});
Map<String, String?>? data = await channel
.invokeMapMethod<String, String?>('Messaging#getCachedToken', {
'appName': app.name,
});

return null;
}
try {
return await FirebaseMessagingWeb(app: app).getCachedToken();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of instantiating a new FirebaseMessagingWeb(app: app) on every token request, you should use FirebaseMessagingPlatform.instanceFor(app: app) to retrieve the cached platform instance. This avoids creating redundant wrapper instances and aligns with the native registrant implementation.

Note: You may need to import package:firebase_messaging_platform_interface/firebase_messaging_platform_interface.dart if it is not already in scope.

Suggested change
return await FirebaseMessagingWeb(app: app).getCachedToken();
return await FirebaseMessagingPlatform.instanceFor(app: app).getCachedToken();

Comment on lines +179 to +191
_delegate;

if (!_initialized) {
// no-op for unsupported browsers
return null;
}

try {
return await _delegate.getToken();
} catch (_) {
// The JS Functions SDK sends no token when Messaging can't produce one.
return null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Evaluating _delegate; outside of the try-catch block can lead to unhandled exceptions if the getter throws during initialization (e.g., in unsupported environments or if the JS SDK fails to load). Moving this evaluation inside the try-catch block ensures that any initialization errors are safely caught and handled, returning null as expected.

    try {
      _delegate;
      if (!_initialized) {
        // no-op for unsupported browsers
        return null;
      }
      return await _delegate.getToken();
    } catch (_) {
      // The JS Functions SDK sends no token when Messaging can't produce one.
      return null;
    }

Messaging#getCachedToken called getToken() unconditionally, so an app
that sends to the installation ID got a legacy token, and with it a
second registration, on its first callable; FCM then rejects sends to
the installation ID. Native Functions reads the manifest meta-data
firebase_messaging_installation_id_enabled and sends no token when it is
true. Do the same: read the key with PackageManager.GET_META_DATA, as
FlutterFirebaseMessagingBackgroundGate does, answer null when it is
true, and warn and fall through when the package manager cannot read
the manifest. The tests app sets the flag, so the Android e2e now
expects null from the provider. Apple and web are unaffected.
melos writes the CHANGELOG sections at release from the commit subjects
that touch each package, so a hand-written section above the generated
ones would be left stranded. The shared App Check instance is described
in the commit that introduces it and in the PR.
///
/// With [limitedUse], the answer is a limited-use token rather than a
/// cached one.
Future<AppCheckInteropToken?> getToken({bool limitedUse = false});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not make the api same to

Future<String?> getToken([bool? forceRefresh])

Future getLimitedUseToken()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, I missed the force refresh here and we can match the separate limited use token method.

I think this is a result of trying to mirror the placeholder for the native cloud functions. AppCheckInteropToken is just a way of passing the placeholder along with error reason. To be more consistent we can leave that helper logic to the consuming packages instead and just return string here.

One other note here is that the scope of the interface here might be too narrow because of my focus on cloud functions port. Is it worth including some of the other APIs that may be shared in other packages like the listeners (Stream<String?> idTokenChanges() and Stream<String?> authStateChanges() in auth, Stream<String?> onTokenChange for app check) and uid in auth.

/// registered for the app.
///
/// Not for app code: use the App Check package's own API instead.
abstract interface class AppCheckTokenProvider implements FirebaseService {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should also add the api of Stream<AppCheckInteropToken?> get onTokenChanged;

/// implementation is registered for the app.
///
/// Not for app code: use the Auth package's own API instead.
abstract interface class AuthTokenProvider implements FirebaseService {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add the api of Stream<String?> get onIdTokenChanged;

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants