firebase_auth_providers_dart 0.4.0
firebase_auth_providers_dart: ^0.4.0 copied to clipboard
Unofficial pure-Dart token providers for firebase_app_dart and cloud_firestore_dart: service accounts, Application Default Credentials and Firebase Auth user sign-in over REST.
0.4.0 #
-
Breaking: the package re-exports
secure_flow, which is now 0.2.0 (new enum values inSecurePresenterKindandRecaptchaAction); exhaustiveswitchstatements over them need the new cases. -
PhoneAuthCredential.toJsonandPhoneAuthCredential.fromJson, in the JSON format of the JS SDK'stoJSONandfromJSON: a verification id with its code, or a temporary proof with its phone number (thecredentialofcredential-already-in-use). As in the JS SDK, empty values are left out and read back as missing, andfromJsonreturns null when all four values are missing; it also returns null for JSON that is not a map or a value that is not a string.toStringstill shows none of the values. -
MultiFactorResolver.session: aMultiFactorSessionof typeMultiFactorSessionType.signInthat wraps the pending credential of the sign-in (resolver.sessionof the JS SDK). It is opaque: no member,toStringor JSON form shows the credential.MultiFactorSessionTypehas the two kinds of the JS SDK,enrollandsignIn, so that aswitchover it stays exhaustive; this package makes noenrollsession yet (its enrolments use the signed-in user). -
The
fromJsonofEmailAuthCredential,OAuthCredentialandPhoneAuthCredential, andOAuthProvider.credentialFromJson, throw aFormatExceptionwithout the text for text that is not JSON. The decoder's exception kept the whole text, with its password, token, SMS code or temporary proof, and printed it. form shows the credential. -
reCAPTCHA Enterprise, as the JS SDK does it:
FirebaseUserAuth.initializeRecaptchaConfig()readsv2/recaptchaConfig(the Enterprise site key and theENFORCE/AUDIT/OFFstate ofEMAIL_PASSWORD_PROVIDERandPHONE_PROVIDER, per tenant) into aRecaptchaConfig, andrecaptchaConfigreturns it. With a token source passed asrecaptchaEnterprise(constructor andforApp), the password sign-in and sign-up, password credentials, and the password reset and email link emails carrycaptchaResponse(captchaRespfor the emails),clientTypeandrecaptchaVersionwhen the provider is protected, and are sent again with a token aftermissing-recaptcha-token. SMS requests with a reCAPTCHA v2 proof read the configuration first, send the Enterprise token when the phone provider is protected, fall back to the v2 token under AUDIT aftermissing-recaptcha-tokenorinvalid-app-credential, and otherwise send the v2 token withcaptchaResponse: NO_RECAPTCHA. A failing source is asked again after the configuration is read again; if it still fails under AUDIT (not a timeout, cancel or overtaken check), the SMS goes with the v2 token and a password request withNO_RECAPTCHA, as in the JS SDK, while ENFORCE throws. The token never shows in an error. Without a source nothing changes. Tested against a fake backend; not run against a real project. -
RecaptchaEnterpriseRequestcarries the EnterprisesiteKey(null before the configuration is read) and thelanguageCode;RecaptchaActionhassignInWithPassword,signUpPasswordandgetOobCode. -
AppVerification.recaptchaV2Loopback()works on the web:secure_flowruns the widget in the app's page there. ARecaptchaFailureof a widget becomesinternal-error,network-request-failedormissing-app-credential. -
Cross-tab sync on the web, as in the JS SDK.
ObservableAuthStorageis anAuthStoragewithchanges(key), a stream that emits when someone else (another tab) changed the key;WebAuthStorage(the browser'sstorageevent),IndexedDbAuthStorage(areadonlyread everypollInterval, 800 ms by default, while the stream is listened to) andBestWebAuthStorage(whichever storage it chose) implement it. The writes of the object itself never emit. The polls stop when nobody listens and atclose(), alsoBestWebAuthStorage.close(), and pause while the page is in the back/forward cache. -
FirebaseUserAuthfollows anObservableAuthStoragewhile it uses it: a sign-out in another tab signs it out, another user signed in there becomes its user, and new tokens or data of the same user are taken over (the ID token stays until the next refresh, which uses the stored refresh token).authStateChanges,idTokenChanges,userChangesandonTokenChangedemit as for a sign-in or sign-out here; thebeforeAuthStateChangedcallbacks do not run. It never writes back what it read. Before it stores an update of the user's session (a rotated refresh token, new user data), it reads the storage and takes over a sign-out or another user stored there instead of writing over it, so a sign-out in one tab is no longer undone by another tab's next write. The JS SDK writes the adopted user back to the persistence; this client does not. Other storages behave as before. -
BestWebAuthStorage: the read of a key marked by a write made without IndexedDB copies the state fromlocalStorageto IndexedDB and now keeps thelocalStoragecopy (only the marker goes), so that a tab that choselocalStorageis not signed out when a tab on IndexedDB follows its write. A copy, once there, follows the writes made with IndexedDB (a sign-out deletes it), and an unmarked copy is deleted at a read only when it differs from IndexedDB. WhenlocalStoragecannot be read for a marked key, the read throws anIndexedDbAuthStorageException(migrate) instead of returning null, which read as a sign-out. -
FirebaseUserAuthreads a change made in another tab only after its own pending writes of the session have finished, so a sign-out or sign-in of this tab whose write is still in flight is not replaced by the value that write replaces, whatever the storage's ordering of reads and writes.
0.3.2 #
FirebaseUserAuth.refreshToken: the refresh token of the signed-in user's session, null when signed out; it follows the server's rotation. It is not a field ofAuthUser(JS hasUser.refreshToken), so a user that is printed or serialized never carries it.- Phone sign-in, with the names of the iOS SDK:
FirebaseUserAuth.verifyPhoneNumber(phoneNumber, appVerification:)sends the SMS code (v1/accounts:sendVerificationCode, with the reCAPTCHA v2 or Enterprise token of theAppVerification, or none for the emulator) and returns the verification id;PhoneAuthProvider.credential( verificationId:, verificationCode:)makes aPhoneAuthCredentialthatsignInWithCredential,linkWithCredential,reauthenticateWithCredentialand the newupdatePhoneNumbertake (v1/accounts:signInWithPhoneNumber). The app asks for the code with its own field. A number that another account has iscredential-already-in-use(also fromPHONE_NUMBER_EXISTS), whosecredentialis aPhoneAuthCredentialof the backend's temporary proof that signs in to that account, as in the iOS SDK; a reauthentication with a number of no account or another account isuser-mismatch.verifyPhoneNumberInteractivelydoes both steps for a program without a code field: the reCAPTCHA page and aCodeEntryFlowofsecure_flow(VM only). Tested with unit tests against a fake backend; not run against the emulator or a real project. - The phone errors map to the codes of the JS SDK and FlutterFire:
INVALID_CODE,INVALID_SESSION_INFO,SESSION_EXPIREDandCODE_EXPIRED,MISSING_CODE(missing-verification-code),MISSING_SESSION_INFO,INVALID_PHONE_NUMBER,MISSING_PHONE_NUMBER,QUOTA_EXCEEDED,TOO_MANY_ATTEMPTS_TRY_LATER,MISSING_APP_CREDENTIAL,INVALID_APP_CREDENTIALandCAPTCHA_CHECK_FAILED. An empty number, verification id or code fails before anything is sent. No error of a phone request holds the phone number, the verification id, the SMS code or the reCAPTCHA token: they are cut from the message, andphoneNumberandserverResponseare left empty. - SMS second factors:
FirebaseUserAuth.startPhoneEnrollment(phoneNumber, appVerification:)sends the code and returns the verification id,finalizePhoneEnrollment(credential, displayName:)enrols the factor (v2/accounts/mfaEnrollment:startand:finalizewith the phone fields), andMultiFactorResolvergetsstartPhoneSignIn(enrollmentId:, appVerification:)andresolveSignInWithPhone(credential)(v2/accounts/mfaSignIn:startand:finalize).unenrollMultiFactorremoves SMS factors as before. An account with SMS factors only now gets the default message ofFirebaseAuthMultiFactorException;unsupportedFactorsMessageis for factors of an unknown kind. Tested with unit tests against a fake backend; not run against the emulator or a real project. IndexedDbAuthStorage: anAuthStoragein IndexedDB for the web (the JS SDK'sindexedDBLocalPersistence), in its own database (firebase_auth_providers_dart, storesessions; not the JS SDK's format). A write completes once its transaction has completed (durability: 'strict'); the calls of one instance run in order; each request hasrequestTimeout(2.5 s by default) and one that takes longer is aborted with anIndexedDbTimeoutException; an open or deletion blocked by another connection fails at once. A connection found closed, or a transaction aborted by the browser, is opened and tried again once. Only the default database is deleted and created again when it exists without the store; another name throws. Errors areIndexedDbAuthStorageExceptions (with anIndexedDbOperationand the browser'sDOMExceptionname and message), which carry no stored value.IndexedDbAuthStorage.isAvailable()probes IndexedDB within the same limit and never throws.BestWebAuthStorage: IndexedDB, elselocalStorage, else memory, decided once by a probe on its own connection (kind, aWebAuthStorageKind), likegetAuthof the JS SDK;close()closes the connection. With IndexedDB, a session of the same key found inlocalStorage(localStoragePrefix) is moved at the first read: written, read back, then deleted fromlocalStorage; a session IndexedDB already has wins and thelocalStoragecopy is deleted. A write made whilelocalStorageor memory holds the sessions leaves a marker inlocalStorageand tries to delete the key from IndexedDB, so the next load with IndexedDB keeps that state.- No cross-tab sync: a sign-out in one tab can be undone by another signed-in tab's next write until it reloads. On
the Dart VM both constructors throw an
UnsupportedError.test/browser/indexed_db_auth_storage_test.dartandtest/browser/web_auth_storage_test.dartpass in headless Chrome with dart2js and dart2wasm.
0.3.1 #
-
The browser flows run on the new package
secure_flow(a new dependency,^0.1.0), whose presenters, environment and errors this library re-exports.authorizeWithOAuthLoopback,signInWithOAuthLoopback,linkWithOAuthLoopbackandreauthenticateWithOAuthLoopbacktake apresenter(aSecurePresenter) and anenvironment(aSecureEnvironment); without a presenter, theOAuthFlowtakes the best one the environment offers: aProviderAppPresenterregistered for the provider, the system browser on a desktop, an in-app browser, the console (only the URL on stderr over SSH or on Linux without a display; a timeout then names thessh -Lforward that would help). A presenter the flow does not accept (a web view, a provider app for another provider) fails with aFirebaseAuthExceptionargument-error, and no presenter for the environment (Android and iOS without one passed) withoperation-not-supported-in-this-environment; both carry theSecureFlowRefusedorSecureFlowNoPresenterofsecure_flowin the newFirebaseAuthException.cause. Before, the flow threw anUnsupportedErroron Android and iOS, where it had no browser launcher. An error of the presenter itself is rethrown as it is.AppVerification.recaptchaV2Loopbackmaps them the same way. -
A
ProviderAppPresenter(the provider's app or SDK; none is part of this package) returns the provider's tokens directly: they go tosignInWithIdpwithout a code exchange, with the raw nonce in the credential for OpenID Connect providers. When a nonce was sent, the ID token must carry it: an ID token without the nonce claim fails withmissing-or-invalid-nonce, like one with another nonce. An access token without an ID token fails withinvalid-oauth-responseunless the provider sets the newOAuthLoopbackProvider.acceptAccessTokenOnly(off by default; such a token has no binding to the request). Tested with a fake presenter only. The redirect URI (http://127.0.0.1:<port>), PKCE, the state and the nonce are unchanged. -
AppVerification.recaptchaV2Loopback(presenter:, environment:, timeout:)serves the reCAPTCHA v2 page with theRecaptchaFlowofsecure_flow; a timeout istimeout. Its site key comes fromgetRecaptchaSiteKey(). Not run against Google. -
FirebaseUserAuth.useEmulator(emulatorHost): sends the later requests to the Auth emulator, for an instance that is created before the emulator is known (FlutterFire'suseAuthEmulator).emulatorHostis now a getter. -
Authenticator app (TOTP) multi-factor authentication, for projects on Identity Platform:
FirebaseUserAuth.startTotpEnrollmentreturns aTotpSecret(secretKey,hashingAlgorithm,codeLength,codeIntervalSeconds,enrollmentCompletionDeadline, andotpauthUri(issuer:, accountName:)for a QR code),finalizeTotpEnrollment(secret, code:, displayName:)finishes the enrolment,unenrollMultiFactor(uid)removes any factor, and the newAuthUser.enrolledFactorslists them (read withaccounts:lookupand stored with the session; storage format still version 2).FirebaseAuthMultiFactorExceptionhas aresolver(MultiFactorResolver.resolveSignInWithTotp(code, enrollmentId:)) that finishes a sign-in or a reauthentication; its message now says when the account's only factors are SMS, which this package cannot use (the resolver then throwsmulti-factor-info-not-found).MultiFactorInfomoved to its own file (same export) and readsenrolledAtstrictly as RFC 3339 with a time zone. The calls go to the Identity Toolkit API v2 as JSON. On 2026-11-20 one run against a real Identity Platform project went through enrolment, sign-in with the second factor and removal, with the errors for an unverified email, a wrong code and a missing display name. Tenants and SMS factors were not part of it. -
Browser sign-in for desktop apps and command line tools (VM only):
FirebaseUserAuth.signInWithOAuthLoopbackandauthorizeWithOAuthLoopback, withOAuthLoopbackProvider.google,.oidcand.discover. The system browser (through apresenter, see thesecure_flowentry below) runs the authorization code flow with PKCE (S256), a randomstate(compared in constant time) and a nonce; the redirect comes back to a one-shot server on 127.0.0.1 that answers 404 to any other path and is always closed (success, error ortimeout). The code is exchanged at the token endpoint with the client id and secret. Google with a "Desktop app" client needs nothing more. The optionalexchangeCodecallback is for a provider that wants a confidential client: it gets the code, the PKCE verifier, the redirect URL and the client id (OAuthAuthorizationCode), sends them to a server of yours, and returns the token endpoint's JSON. It is the counterpart ofserverAuthCodeingoogle_sign_in. The result (OAuthLoopbackResult) has the provider's tokens and a readyOAuthCredential. On the web these throw anUnsupportedError. New error codes:timeout,user-cancelled,invalid-oauth-response,invalid-oauth-provider. Only the redirect of this sign-in (itsHostheader and itsstate) ends the wait; any other request gets a 400. The code exchange and the discovery request fail withnetwork-request-failedafter 30 seconds. Plainhttpendpoints are accepted only on127.0.0.1and::1. -
FirebaseUserAuth.linkWithOAuthLoopbackandreauthenticateWithOAuthLoopback: the same browser sign-in, thenlinkWithCredentialorreauthenticateWithCredential. Same arguments assignInWithOAuthLoopback;null-userbefore the browser opens when nobody is signed in. -
On 2026-11-20, Google sign-in with a Desktop client was run against a real Firebase project: the code was exchanged directly with the client secret and PKCE, and the redirect was
http://127.0.0.1:<port>.exchangeCodeand generic OpenID Connect providers were run only against the fake identity provider of the tests. -
OAuthLoopbackProvider.github: GitHub sign-in through the loopback helper (PKCE S256, client secret, default scopesread:user user:email, no nonce; Firebase gets the access token only). Run only against the fake identity provider of the tests. -
A backend error ends the session only when it comes with HTTP 400:
invalidatesSessionis false for a 5xx that namesTOKEN_EXPIRED,USER_DISABLED, ..., and the user stays signed in. -
When a request with the ID token is rejected with
TOKEN_EXPIREDorINVALID_ID_TOKEN, the token is refreshed once to check the session (as in the iOS SDK): the user is signed out only when the refresh says that the session ended, and otherwise the request is sent once more with the new token. -
Token lifetimes from the backend are bounded as in the iOS SDK: an
expiresInoutside of (0, 24 h], missing or not a number counts as one hour, anexpclaim more than 24 h ahead is not trusted, and a proactive refresh delay beyond 24 h refreshes right away. -
Every request is bounded by
requestTimeout(a new named parameter ofFirebaseUserAuth, 30 s by default): a request that takes longer fails withnetwork-request-failed, and the next token request tries again. The proactive token refresh retries with backoff after any error that does not end the session (a failing storage, for example), not only after aFirebaseAuthException. A storage that throws on read inrestorekeeps the stored session (tested; the behavior was already so). -
FirebaseUserAuth.revokeToken(authorizationCode)revokes the Sign in with Apple token of the signed-in user with Apple's authorization code (v2/accounts:revokeToken, likerevokeToken(withAuthorizationCode:)of the iOS SDK). The user stays signed in. Throwsnull-userwhen nobody is signed in. Sends thetenantIdwhen one is set, like the JS SDK'srevokeTokenrequest. Tested with a fake HTTP client only. -
FirebaseUserAuth.revokeAccessToken(token)revokes a Sign in with Apple access token of the signed-in user (revokeAccessTokenof the JS SDK:v2/accounts:revokeTokenwith the token typeACCESS_TOKENand thetenantIdwhen set). The user stays signed in. Throwsnull-userwhen nobody is signed in, where the JS SDK does nothing. Tested with a fake HTTP client only. -
A storage that fails to write a new session no longer leaves the stored session behind for good: the session in memory is the new one (the backend may have replaced the refresh token), the operation throws the error of the storage, and the next session change (a token refresh, a reload, a sign-in) writes it again, even when the refresh token did not change. The user is not signed out.
-
FirebaseUserAuth.forAppsetsapp.authProvidereven when thereadof the storage throws, then rethrows: the app works signed out, andrestore()on that instance tries again. -
signOutwith a storage that fails to delete the session signs the user out in memory (the streams emit null) and throws the error of the storage;restore()on that instance deletes the stored session again instead of signing the user back in. A new instance still restores it until a write succeeds. -
JSON for credentials in the format of the JS SDK:
EmailAuthCredential.toJson/fromJson,OAuthCredential.toJson/fromJsonandOAuthProvider.credentialFromJson(toJSON,fromJSONandcredentialFromJSONof the JS SDK).fromJsonreturns null for JSON that is not a credential, as in the JS SDK;credentialFromJsonthrows anArgumentError. An email link is written as its code and tenant, as in the JS SDK. The JSON holds the credential's password or tokens. Tested with fixtures derived from the JS sources only. -
FirebaseUserAuth.emulatorConfig(AuthEmulatorConfig: protocol, host, port, options), like the JS SDK'semulatorConfig; null without an emulator.emulatorOptions: AuthEmulatorOptions(disableWarnings: true)on the constructor andforApp, andoptions:onuseEmulator, leave out the warning for an emulator off the loopback interface. An invalid emulator host stays anArgumentError(the JS SDK'sinvalid-emulator-schemeis aFirebaseAuthException); a scheme other thanhttporhttpsnow says so in the message. -
AuthUser.providerId(alwaysfirebase),UserCredential.operationType(the newOperationTypeenum:signIn,link,reauthenticate, with the JS SDK's strings invalue) andAuthUser.toJson()with the keys of the JS SDK'sUser.toJSON, exceptstsTokenManager,apiKeyandappName, which belong to the session. -
On 2026-11-20, a generic OpenID Connect provider was run against a real Firebase project with
discoverand with anexchangeCodecallback, and GitHub with a real OAuth App (account-exists-with-different-credential, then link and unlink on an existing account). The backend accepts only a token of the GitHub app configured in the project, and the callback URL of the app must behttp://127.0.0.1without a/at the end. All of it is in the README. -
FirebaseUserAuth.setStorage(storage)keeps the session in anotherAuthStoragefrom now on and moves the current one there (setPersistenceof the JS SDK). The session is written to the new storage first and deleted from the old one after; when the write fails, nothing changes. -
OAuthLoopbackProvider.copyWith(scopes:, customParameters:). -
A call after
disposethrowsFirebaseUserAuthDisposedError, aStateError. -
FirebaseUserAuth.app: the app of an instance made byforApp; null for one made with the constructor. -
Constants
ProviderId,SignInMethod,FactorIdandAuthErrorCode(the codes of the JS SDK and the five only this client has).MultiFactorInfo.phoneFactorIdandtotpFactorIdare theFactorIdvalues. -
FirebaseAuthException.serverResponse: the answer of the backend on the errors the JS SDK tags with it (account-exists-with-different-credential,credential-already-in-use,email-already-in-use,user-disabled). It is unmodifiable, and neither it nor the exception prints its values. -
A change of the account (email verification,
verifyBeforeUpdateEmail, linking, TOTP enrolment and unenrolment, email and password updates) is no longer sent a second time when the backend rejects the ID token of the account read that follows it.
0.3.0 #
- The complete server error map of the JS SDK (
SERVER_ERROR_MAPof@firebase/auth1.13.10): the phone, multi-factor, reCAPTCHA,signInWithIdpand action code settings codes are mapped like the JS SDK maps them (INVALID_CODEisinvalid-verification-code,UNAUTHORIZED_DOMAINisunauthorized-continue-uri, ...), with the JS SDK's messages. Codes that were already mapped are unchanged. - Fix: an answer with HTTP 200 whose body has an
errorMessagewas taken for a success; it is an error now, like in the JS SDK. An answer withneedConfirmationthrowsaccount-exists-with-different-credential. FirebaseAuthExceptionhas FlutterFire'semail,phoneNumberandtenantId, set for the errors the JS SDK tags with the answer (credential-already-in-use,email-already-in-use,user-disabled,account-exists-with-different-credential).- Fix:
checkActionCodethrewinternal-errorfor an operation the package does not know; it returns it, like the JS SDK, as the newActionCodeOperation.unknownwith the backend's name in the newActionCodeInfo.requestType. Breaking for aswitchoverActionCodeOperationwithout a default: add a case forunknown(FlutterFire'sActionCodeInfoOperationhas the same value).ActionCodeInfo.multiFactorInfois the factor ofrevertSecondFactorAddition, which now requires it, like the JS SDK. - The full user record, like FlutterFire's
User:AuthUser.providerData(a list of the newUserInfo),metadata(the newUserMetadata: creation and last sign-in time),phoneNumber,tenantId, andphotoURL(the FlutterFire name ofphotoUrl). Like the JS SDK, every sign-in now reads the account (accounts:lookup) before it completes, so a sign-in makes two requests; a sign-in whose account cannot be read fails and signs nobody in.reloadreads the same fields. - The sign-in methods and
reauthenticateWithEmailAndPasswordreturn aUserCredential(FlutterFire's name), which is also theAuthUserthey returned before:userand the newadditionalUserInfo(AdditionalUserInfo:isNewUser,providerId,profile,username). Code that reads the result as anAuthUseris unchanged; breaking only for classes that implement or mockFirebaseUserAuthand return anAuthUserfrom these methods. - The stored session has a version (2) and the whole record. Sessions stored by 0.1 and 0.2 are still restored;
their user lacks the new fields until
reload. authStateChanges()andidTokenChanges()(FlutterFire's streams): they start with the current user (after arestorein progress) and then follow sign-ins of another user and sign-outs, and, foridTokenChanges(), every new ID token.userChanges()is unchanged (it still does not emit the current user when listened to).authStateReady(),beforeAuthStateChanged(callback, onAbort:)(a throwing callback blocks the sign-in, sign-out or switch withlogin-blocked) andupdateCurrentUser(user)(continue the session of a user of another instance with the same API key), from the JS SDK. The token stream Firestore follows (onTokenChanged) emits as before;updateCurrentUseris a user switch for it.languageCode,setLanguageCode(FlutterFire) anduseDeviceLanguage()(JS SDK): the language of the emails the backend sends, inX-Firebase-Localeof every Identity Toolkit request. The device language isPlatform.localeNameon the VM andnavigator.languagesin a browser. New dependency:web(already in the dependency graph throughhttp).tenantId(Identity Platform multi-tenancy), sent with the requests the JS SDK sends it with (sign-ins, action code requests,createAuthUri); a sign-in orupdateCurrentUserof a user of another tenant throwstenant-id-mismatch, like the JS SDK.- Email link sign-in:
sendSignInLinkToEmail(email:, actionCodeSettings:),isSignInWithEmailLink(link),signInWithEmailLink(email:, emailLink:), andActionCodeURL.parseLink(link)(the JS SDK'sparseActionCodeURL, with its Dynamic Link and iOS deep link unwrapping). - Credentials:
AuthCredential,EmailAuthCredentialandEmailAuthProvider.credential/credentialWithLink(FlutterFire names), withsignInWithCredential,linkWithCredential(an email and password or an email link to an anonymous user, for example) andreauthenticateWithCredential.reauthenticateWithEmailAndPasswordstays, as a shortcut for the latter. New error codes from the JS SDK:provider-already-linked,argument-error,login-blocked,tenant-id-mismatch. - Federated sign-in by token exchange:
OAuthCredentialand the providersGoogleAuthProvider,AppleAuthProvider(withcredentialWithIDTokenand its raw nonce),FacebookAuthProvider,GithubAuthProvider,TwitterAuthProvider,MicrosoftAuthProvider,YahooAuthProviderandOAuthProvider(providerId)(oidc.*and any other id), with FlutterFire's names. The app gets the provider's ID or access token itself;signInWithCredential,linkWithCredentialandreauthenticateWithCredentialexchange it throughaccounts:signInWithIdpwith the request of the JS SDK.unlink(providerId)removes a sign-in method. UserCredential.credentialandFirebaseAuthException.credential: the provider's credential the backend returned, so thataccount-exists-with-different-credentialandcredential-already-in-usecan be recovered (sign in with the existing method, then link). New error codes:no-such-provider.validatePassword(password)with the newPasswordPolicyandPasswordValidationStatus(FlutterFire's names): the project's (or tenant's) policy is fetched once fromv2/passwordPolicy, cached, and fetched again afterpassword-does-not-meet-requirements, like the JS SDK. The Auth emulator does not implement the endpoint.- Ready-made storages:
FileAuthStorage(path)on the Dart VM (a JSON file written atomically and owner-only: on Linux and macOS it is written in a new staging directory with mode 0700, checked before anything is written, and renamed into place with mode 0600; on Windows it inherits the access list of its directory) andWebAuthStorage.session()/WebAuthStorage.local()in a browser (sessionStorage/localStorage), exported through conditional imports so that the library still compiles everywhere (each throwsUnsupportedErroron the other platform). Their documentation says what a stored refresh token exposes.example/persistent_session.dartusesFileAuthStorage.FileAuthStorageis exported from the main library: breaking for an app that declared its ownFileAuthStorage(as the 0.2 docs and example suggested) in another library and imports both, which is now anambiguous_import; rename the class or import the package withhide FileAuthStorage. - Fix: a token refresh or an operation of the signed-in user (a profile update, a link, an unlink) that completed
after another user signed in could write the tokens or data of the previous user into the new session and its
storage. Each operation now belongs to the session it started in, and its result is dropped once another session
is installed or the session is cleared. A sign-in that fails or is blocked no longer cancels the operations of the
signed-in user, and
signOut()afterdispose()throws aStateErrorinstead of deleting the stored session. - Documentation: the README, the authentication guide and the API docs cover the new sign-in methods, streams,
tenants, language, password policy and storages; a new example,
example/linking_and_email_link.dart.
0.2.1 #
- Fix: signing in (
signInWithEmailAndPassword,signInWithCustomToken) or reauthenticating (reauthenticateWithEmailAndPassword) with an account that has a second factor threwinternal-error("did not return tokens"). It now throws aFirebaseAuthMultiFactorExceptionwith the codemulti-factor-auth-required, like the JS SDK, carrying thependingCredentialand the enrolled factors (hints, a list of the newMultiFactorInfo). Signing in with a second factor is still not supported. Additive; nothing changes for accounts without a second factor.
0.2.0 #
Breaking: the calls that FlutterFire's firebase_auth also has take its arguments. Every change
is in docs/api_migration_0_2.md.
FirebaseAuthException(wasFirebaseAuthProviderException) extendsFirebaseException.signInWithEmailAndPassword,createUserWithEmailAndPassword,reauthenticateWithEmailAndPassword,sendPasswordResetEmailandconfirmPasswordResettake named arguments;userChanges()is a method.- Token providers implement
AuthTokenProvider(wasInternalTokenProvider) offirebase_app_dart0.2. - New, additive:
ServiceAccountKey(parses a key file and signs with RS256, the signer ofOAuthTokenProvider.serviceAccount) andFirebaseUserAuth.emulatorOrigin(the emulator host check of the constructor), forfirebase_admin_dart. Nothing else changes.
0.1.1 #
Documentation and examples only. The library behaves exactly as in 0.1.0; the only code
change is the version in FirebaseUserAuth.clientVersion.
- Doc comments with compiling samples across the public API.
- A rewritten README, and one example per task in
example/: email and password, account flows, custom tokens, a persistent session, a service account, Application Default Credentials and wiring intocloud_firestore_dart.
0.1.0 #
First version.
-
Licensed under Apache-2.0 (see
LICENSEandNOTICE), likecloud_firestore_dartandfirebase_app_dart; the_vmpackages they replace were licensed under BSD-3-Clause. -
FirebaseUserAuth: Firebase Auth user sign-in over the Identity Toolkit and Secure Token REST APIs (anonymous, email and password, custom token), ID token refresh on demand and ahead of expiry, sign-out,AuthStoragefor the session (in memory by default), Auth emulator support. It implements the token provider interface offirebase_app_dart, socloud_firestore_dartsends the ID token and follows user switches. Every request carries the headers of the JS SDK:X-Client-Version(FirebaseUserAuth.clientVersion),X-Firebase-gmpid(theappIdparameter) andX-Firebase-AppCheck(theappCheckparameter);forApptakes both from the app. -
FirebaseUserAuthaccount management, ported from the REST-backed operations of the JS SDK:sendPasswordResetEmail,confirmPasswordReset,verifyPasswordResetCode,checkActionCode,applyActionCode,sendEmailVerification,verifyBeforeUpdateEmail,updateEmail,updatePassword,updateProfile,reauthenticateWithEmailAndPassword,reload,deleteCurrentUserandfetchSignInMethodsForEmail, withActionCodeSettings,ActionCodeInfoandActionCodeOperation.AuthUserhasemailVerified,displayNameandphotoUrl, stored with the session;userChangesalso emits after a change of the user's data. Error codes follow the JS SDK's map of server codes (an unknown code is its kebab case form). -
The Auth emulator host is checked like the Firestore host: user info, a path, a query, a bad port and Google hosts throw an
ArgumentError;http://andhttps://URLs are accepted asconnectAuthEmulatortakes them, and an emulator off the loopback interface logs a warning. The stored refresh token is a credential; theAuthStoragedocs say how to protect it. -
OAuthTokenProvider.serviceAccountand, inadc.dart,applicationDefaultCredentials(): OAuth 2.0 access tokens for servers and command line tools. These bypass security rules. The RS256 signer of the service account assertion blinds the message and verifies each signature before using it. -
Web-compatible main library (no
dart:io);FirebaseUserAuthwas run in Chrome (dart2js and dart2wasm) against the Auth emulator. -
Requires Dart 3.8.0 or later.
Verified with unit tests and against the Firebase Auth and Firestore emulators only. Nothing was run against the real Firebase Auth service or Google's token endpoint.