Repository navigation
feat(core): add token providers for Auth, App Check and Messaging - #19009
jonathanedey wants to merge 6 commits into
Conversation
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.
There was a problem hiding this comment.
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.
| Map<String, String?>? data = await channel | ||
| .invokeMapMethod<String, String>('Messaging#getCachedToken', { | ||
| 'appName': app.name, | ||
| }); |
There was a problem hiding this comment.
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.
| 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(); |
There was a problem hiding this comment.
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.
| return await FirebaseMessagingWeb(app: app).getCachedToken(); | |
| return await FirebaseMessagingPlatform.instanceFor(app: app).getCachedToken(); |
| _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; | ||
| } |
There was a problem hiding this comment.
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}); |
There was a problem hiding this comment.
why not make the api same to
Future<String?> getToken([bool? forceRefresh])
Future getLimitedUseToken()
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
Add the api of Stream<String?> get onIdTokenChanged;
Description
Dart-only Firebase packages (
firebase_ai,firebase_data_connect, pure-Dartcloud_functions) attach Auth, App Check, and FCM tokens to their own requests. Today they get them by hard-depending onfirebase_auth,firebase_app_check, andfirebase_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 infirebase_core_interface; each plugin registers an implementation per app at startup (dartPluginClassregistrant on native,registerWithon web); consumers callapp.getService<T>().firebase_core's public API is unchanged. Consumers migrate in follow-up PRs.Change highlights:
main, so a user restored from a previous launch gets a token on cold start. App Check answers the placeholder plus a reason beforeactivate(), matching native Functions.null. Each matches its native shape; the doc comments say why.getToken(), as native Functions does. Web reads only when permission is already granted. Default app only.firebase_app_check_webbehavior change: all delegates of an app now share one activated JS instance. Needed so the provider sees the app's activation; a secondactivate()is a no-op.All three providers ship in the same
firebase_coremajor so an old plugin can never resolve against a new consumer and silently drop a header.Checklist
///).melos run analyze) does not report any problems on my PR.Breaking Change