firebase::auth::Auth

#include <auth.h>

Firebase authentication object.

Summary

firebase::auth::Auth is the gateway to the Firebase authentication API. With it, you can referencefirebase::auth::User objects to manage user accounts and credentials.

Eachfirebase::App has up to onefirebase::auth::Auth class. You acquire thefirebase::auth::Auth class through the static functionfirebase::auth::Auth::GetAuth.

For example:

// Get the Auth class for your App.firebase::auth::Auth*auth=firebase::auth::Auth::GetAuth(app);// Request anonymous sign-in and wait until asynchronous call completes.firebase::Future<firebase::auth::AuthResult>sign_in_future=auth->SignInAnonymously();while(sign_in_future.status()==firebase::kFutureStatusPending){// when polling, like this, make sure you service your platform's// message loop// see https://github.com/firebase/quickstart-cpp for a sampleProcessEvents(300);std::cout<<"Signing in...\n";}constfirebase::auth::AuthErrorerror=static_cast<firebase::auth::AuthError>(sign_in_future.error());if(error!=firebase::auth::kAuthErrorNone){std::cout<<"Sign in failed with error '"<<sign_in_future.error_message()<<"'\n";}else{firebase::auth::Useruser=sign_in_future.result()->user;// is_anonymous from Anonymousstd::cout<<"Signed in as "<<(user.is_anonymous()?"an anonymous":"a non-anonymous")<<" user\n";}

Constructors and Destructors

~Auth()

Public functions

AddAuthStateListener(AuthStateListener *listener)
void
Registers a listener to changes in the authentication state.
AddIdTokenListener(IdTokenListener *listener)
void
Registers a listener to changes in the ID token state.
CreateUserWithEmailAndPassword(const char *email, const char *password)
Creates, and on success, logs in a user with the given email address and password.
CreateUserWithEmailAndPasswordLastResult() const
Get results of the most recent call to CreateUserWithEmailAndPassword.
FetchProvidersForEmail(const char *email)
Asynchronously requests the IDPs (identity providers) that can be used for the given email address.
FetchProvidersForEmailLastResult() const
Get results of the most recent call to FetchProvidersForEmail.
RemoveAuthStateListener(AuthStateListener *listener)
void
Unregisters a listener of authentication changes.
RemoveIdTokenListener(IdTokenListener *listener)
void
Unregisters a listener of ID token changes.
SendPasswordResetEmail(const char *email)
Future< void >
Initiates a password reset for the given email address.
SendPasswordResetEmailLastResult() const
Future< void >
Get results of the most recent call to SendPasswordResetEmail.
SignInAndRetrieveDataWithCredential(constCredential & credential)
Asynchronously logs into Firebase with the given credentials.
SignInAndRetrieveDataWithCredentialLastResult() const
Get results of the most recent call to SignInAndRetrieveDataWithCredential.
SignInAnonymously()
Asynchronously creates and becomes an anonymous user.
SignInAnonymouslyLastResult() const
Get results of the most recent call to SignInAnonymously.
SignInWithCredential(constCredential & credential)
Convenience method for SignInAndRetrieveDataWithCredential that doesn't return additional identity provider data.
SignInWithCustomToken(const char *custom_token)
Asynchronously logs into Firebase with the givenAuth token.
SignInWithCustomTokenLastResult() const
Get results of the most recent call to SignInWithCustomToken.
SignInWithEmailAndPassword(const char *email, const char *password)
Signs in using provided email address and password.
SignInWithEmailAndPasswordLastResult() const
Get results of the most recent call to SignInWithEmailAndPassword.
SignInWithProvider(FederatedAuthProvider *provider)
Sign-in a user authenticated via a federated auth provider.
SignOut()
void
Removes any existing authentication credentials from this client.
UseAppLanguage()
void
Sets the user-facing language code to be the default app language.
UseEmulator(std::string host, uint32_t port)
void
Modify thisAuth instance to communicate with the Firebase Authentication emulator.
app()
App &
Gets theApp this auth object is connected to.
current_user()
Synchronously gets the cached current user, or returns an object where is_valid() == false if there is none.
language_code() const
std::string
The current user language code.
set_language_code(const char *language_code)
void
Sets the user-facing language code for auth operations that can be internationalized, such as FirebaseUser.sendEmailVerification().

Public static functions

GetAuth(App *app,InitResult *init_result_out)
Returns theAuth object for anApp.

Structs

firebase::auth::Auth::FetchProvidersResult

Results of calls FetchProvidersForEmail.

Public functions

AddAuthStateListener

voidAddAuthStateListener(AuthStateListener*listener)

Registers a listener to changes in the authentication state.

There can be more than one listener registered at the same time. The listeners are called asynchronously, possibly on a different thread.

Authentication state changes are:

  • Right after the listener has been registered
  • When a user signs in
  • When the current user signs out
  • When the current user changes

It is a recommended practice to always listen to sign-out events, as you may want to prompt the user to sign in again and maybe restrict the information or actions they have access to.

Use RemoveAuthStateListener to unregister a listener.

Note: The caller ownslistener and is responsible for destroying it. Whenlistener is destroyed, or whenAuth is destroyed, RemoveAuthStateListener is called automatically.

AddIdTokenListener

voidAddIdTokenListener(IdTokenListener*listener)

Registers a listener to changes in the ID token state.

There can be more than one listener registered at the same time. The listeners are called asynchronously, possibly on a different thread.

Authentication state changes are:

  • Right after the listener has been registered
  • When a user signs in
  • When the current user signs out
  • When the current user changes
  • When there is a change in the current user's token

Use RemoveIdTokenListener to unregister a listener.

Note: The caller ownslistener and is responsible for destroying it. Whenlistener is destroyed, or whenAuth is destroyed, RemoveIdTokenListener is called automatically.

CreateUserWithEmailAndPassword

Future<AuthResult>CreateUserWithEmailAndPassword(constchar*email,constchar*password)

Creates, and on success, logs in a user with the given email address and password.

An error is returned when account creation is unsuccessful (due to another existing account, invalid password, etc.).

CreateUserWithEmailAndPasswordLastResult

Future<AuthResult>CreateUserWithEmailAndPasswordLastResult()const

Get results of the most recent call to CreateUserWithEmailAndPassword.

FetchProvidersForEmail

Future<FetchProvidersResult>FetchProvidersForEmail(constchar*email)

Asynchronously requests the IDPs (identity providers) that can be used for the given email address.

Useful for an "identifier-first" login flow.

The following sample code illustrates a possible login screen that allows the user to pick an identity provider.

// This function is called every frame to display the login screen.// Returns the identity provider name, or "" if none selected.constchar*DisplayIdentityProviders(firebase::auth::Auth&auth,constchar*email){// Get results of most recent call to FetchProvidersForEmail().firebase::Future<firebase::auth::Auth::FetchProvidersResult>future=auth.FetchProvidersForEmailLastResult();constfirebase::auth::Auth::FetchProvidersResult*result=future.result();// Header.ShowTextBox("Sign in %s",email);// Fetch providers from the server if we need to.constboolrefetch=future.status()==firebase::kFutureStatusInvalid||(result!=nullptr&&strcmp(email,result->email.c_str())!=0);if(refetch){auth.FetchProvidersForEmail(email);}// Show a waiting icon if we're waiting for the asynchronous call to// complete.if(future.status()!=firebase::kFutureStatusComplete){ShowImage("waiting icon");return"";}// Show error code if the call failed.if(future.error()!=firebase::auth::kAuthErrorNone){ShowTextBox("Error fetching providers: %s",future.error_message());}// Show a button for each provider available to this email.// Return the provider for the button that's pressed.for(size_ti=0;i<result->providers.size();++i){constboolselected=ShowTextButton(result->providers[i].c_str());if(selected)returnresult->providers[i].c_str();}return"";}

FetchProvidersForEmailLastResult

Future<FetchProvidersResult>FetchProvidersForEmailLastResult()const

Get results of the most recent call to FetchProvidersForEmail.

RemoveAuthStateListener

voidRemoveAuthStateListener(AuthStateListener*listener)

Unregisters a listener of authentication changes.

Listener must previously been added with AddAuthStateListener.

Note that listeners unregister themselves automatically when they are destroyed, and theAuth class unregisters its listeners when theAuth class itself is destroyed, so this function does not normally need to be called explicitly.

RemoveIdTokenListener

voidRemoveIdTokenListener(IdTokenListener*listener)

Unregisters a listener of ID token changes.

Listener must previously been added with AddIdTokenListener.

Note that listeners unregister themselves automatically when they are destroyed, and theAuth class unregisters its listeners when theAuth class itself is destroyed, so this function does not normally need to be called explicitly.

SendPasswordResetEmail

Future<void>SendPasswordResetEmail(constchar*email)

Initiates a password reset for the given email address.

If the email address is not registered, then the returned task has a status of IsFaulted.

The following sample code illustrating a possible password reset flow. Like in the Anonymous Sign-In example above, the ResetPasswordScreen() function is called once per frame (say 30 times per second).

No state is persisted by the caller in this example. The state of the most recent calls are instead accessed through calls to functions like auth.SendPasswordResetEmailLastResult().

constchar*ImageNameForStatus(constfirebase::FutureBase&future){assert(future.status()!=firebase::kFutureStatusInvalid);returnfuture.status()==firebase::kFutureStatusPending?"waiting icon":future.error()==firebase::auth::kAuthErrorNone?"checkmark icon":"x mark icon";}// This function is called once per frame.voidResetPasswordScreen(firebase::auth::Auth&auth){// Gather email address.// ShowInputBox() returns a value when `enter` is pressed.conststd::stringemail=ShowInputBox("Enter e-mail");if(email!=""){auth.SendPasswordResetEmail(email.c_str());}// Show checkmark, X-mark, or waiting icon beside the// email input box, to indicate if email has been sent.firebase::Futuresend_future=auth.SendPasswordResetEmailLastResult();ShowImage(ImageNameForStatus(send_future));// Display error message if the e-mail could not be sent.if(send_future.status()==firebase::kFutureStatusComplete&&send_future.error()!=firebase::auth::kAuthErrorNone){ShowTextBox(send_future.error_message());}}

SendPasswordResetEmailLastResult

Future<void>SendPasswordResetEmailLastResult()const

Get results of the most recent call to SendPasswordResetEmail.

SignInAndRetrieveDataWithCredential

Future<AuthResult>SignInAndRetrieveDataWithCredential(constCredential&credential)

Asynchronously logs into Firebase with the given credentials.

For example, the credential could wrap a Facebook login access token or a Twitter token/token-secret pair.

TheAuthResult contains both a reference to theUser (which is_valid() will return false if the sign in failed), andAdditionalUserInfo, which holds details specific to the Identity Provider used to sign in.

An error is returned if the token is invalid, expired, or otherwise not accepted by the server.

SignInAndRetrieveDataWithCredentialLastResult

Future<AuthResult>SignInAndRetrieveDataWithCredentialLastResult()const

Get results of the most recent call to SignInAndRetrieveDataWithCredential.

SignInAnonymously

Future<AuthResult>SignInAnonymously()

Asynchronously creates and becomes an anonymous user.

If there is already an anonymous user signed in, that user will be returned instead. If there is any other existing user, that user will be signed out.

The following sample code illustrates the sign-in flow that might be used by a game or some other program with a regular (for example, 30Hz) update loop.

The sample calls SignIn() every frame. We don’t maintain our own Futures but instead callSignInAnonymouslyLastResult() to get theFuture of our most recent call.

// Try to ensure that we get logged in.// This function is called every frame.boolSignIn(firebase::auth::Auth&auth){// Grab the result of the latest sign-in attempt.firebase::Future<firebase::auth::AuthResult>future=auth.SignInAnonymouslyLastResult();// If we're in a state where we can try to sign in, do so.if(future.status()==firebase::kFutureStatusInvalid||(future.status()==firebase::kFutureStatusComplete&&future.error()!=firebase::auth::kAuthErrorNone)){auth.SignInAnonymously();}// We're signed in if the most recent result was successful.returnfuture.status()==firebase::kFutureStatusComplete&&future.error()==firebase::auth::kAuthErrorNone;}

SignInAnonymouslyLastResult

Future<AuthResult>SignInAnonymouslyLastResult()const

Get results of the most recent call to SignInAnonymously.

SignInWithCredential

Future<User>SignInWithCredential(constCredential&credential)

Convenience method for SignInAndRetrieveDataWithCredential that doesn't return additional identity provider data.

SignInWithCustomToken

Future<AuthResult>SignInWithCustomToken(constchar*custom_token)

Asynchronously logs into Firebase with the givenAuth token.

An error is returned if the token is invalid, expired or otherwise not accepted by the server.

SignInWithCustomTokenLastResult

Future<AuthResult>SignInWithCustomTokenLastResult()const

Get results of the most recent call to SignInWithCustomToken.

SignInWithEmailAndPassword

Future<AuthResult>SignInWithEmailAndPassword(constchar*email,constchar*password)

Signs in using provided email address and password.

An error is returned if the password is wrong or otherwise not accepted by the server.

SignInWithEmailAndPasswordLastResult

Future<AuthResult>SignInWithEmailAndPasswordLastResult()const

Get results of the most recent call to SignInWithEmailAndPassword.

SignInWithProvider

Future<AuthResult>SignInWithProvider(FederatedAuthProvider*provider)

Sign-in a user authenticated via a federated auth provider.

Note: : This operation is supported only on iOS, tvOS and Android platforms. On other platforms this method will return aFuture with a preset error code: kAuthErrorUnimplemented.

Details
Parameters
provider
Contains information on the provider to authenticate with.
Returns
AFuture with the result of the sign-in request.

SignOut

voidSignOut()

Removes any existing authentication credentials from this client.

This function always succeeds.

UseAppLanguage

voidUseAppLanguage()

Sets the user-facing language code to be the default app language.

This uses a language associated with the device's locale data. On desktop this will set the language code to the Firebase service's default. You may subsequently customize the language code again by invokingset_language_code().

UseEmulator

voidUseEmulator(std::stringhost,uint32_tport)

Modify thisAuth instance to communicate with the Firebase Authentication emulator.

app

App&app()

Gets theApp this auth object is connected to.

current_user

Usercurrent_user()

Synchronously gets the cached current user, or returns an object where is_valid() == false if there is none.

Note: This function may block and wait until theAuth instance finishes loading the saved user's state. This should only happen for a short time after theAuth instance is created.

language_code

std::stringlanguage_code()const

The current user language code.

This can be set to the app’s current language by calling set_language_code. The string must be a language code that follows BCP 47. This will return an empty string if the app default language code is being used.

set_language_code

voidset_language_code(constchar*language_code)

Sets the user-facing language code for auth operations that can be internationalized, such as FirebaseUser.sendEmailVerification().

This language code should follow the conventions defined by the IETF in BCP 47.

~Auth

~Auth()

Public static functions

GetAuth

Auth*GetAuth(App*app,InitResult*init_result_out)

Returns theAuth object for anApp.

Creates theAuth if required.

To get theAuth object for the default app, use, GetAuth(GetDefaultFirebaseApp());

If the libraryAuth fails to initialize, init_result_out will be written with the result status (if a pointer is given).

Details
Parameters
app
TheApp to use for theAuth object.
init_result_out
Optional: If provided, write the init result here. Will be set to kInitResultSuccess if initialization succeeded, or kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-05-07 UTC.