firebase_admin.auth module

Firebase Authentication module.

This module contains functions for minting and verifying JWTs used for authenticating against Firebase services. It also provides functions for creating and managing user accounts in Firebase projects.

Exceptions

exception firebase_admin.auth.AuthError(code, message, error=None)

Bases: exceptions.Exception

Represents an Exception encountered while invoking the Firebase auth API.

Classes

class firebase_admin.auth.ErrorInfo(error)

Bases: object

Represents an error encountered while importing an ImportUserRecord.

index
reason
class firebase_admin.auth.ExportedUserRecord(data)

Bases: firebase_admin._user_mgt.UserRecord

Contains metadata associated with a user including password hash and salt.

password_hash

The user’s password hash as a base64-encoded string.

If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password hash of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is None.

password_salt

The user’s password salt as a base64-encoded string.

If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password salt of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is None.

class firebase_admin.auth.ImportUserRecord(uid, email=None, email_verified=None, display_name=None, phone_number=None, photo_url=None, disabled=None, user_metadata=None, provider_data=None, custom_claims=None, password_hash=None, password_salt=None)

Bases: object

Represents a user account to be imported to Firebase Auth.

Must specify the uid field at a minimum. A sequence of ImportUserRecord objects can be passed to the auth.import_users() function, in order to import those users into Firebase Auth in bulk. If the password_hash is set on a user, a hash configuration must be specified when calling import_users().

Parameters:
  • uid – User’s unique ID. Must be a non-empty string not longer than 128 characters.
  • email – User’s email address (optional).
  • email_verified – A boolean indicating whether the user’s email has been verified (optional).
  • display_name – User’s display name (optional).
  • phone_number – User’s phone number (optional).
  • photo_url – User’s photo URL (optional).
  • disabled – A boolean indicating whether this user account has been disabled (optional).
  • user_metadata – An auth.UserMetadata instance with additional user metadata (optional).
  • provider_data – A list of auth.UserProvider instances (optional).
  • custom_claims – A dict of custom claims to be set on the user account (optional).
  • password_hash – User’s password hash as a bytes sequence (optional).
  • password_salt – User’s password salt as a bytes sequence (optional).
Raises:

ValueError – If provided arguments are invalid.

to_dict()

Returns a dict representation of the user. For internal use only.

custom_claims
display_name
email
password_hash
password_salt
phone_number
photo_url
provider_data
uid
user_metadata
class firebase_admin.auth.ListUsersPage(download, page_token, max_results)

Bases: object

Represents a page of user records exported from a Firebase project.

Provides methods for traversing the user accounts included in this page, as well as retrieving subsequent pages of users. The iterator returned by iterate_all() can be used to iterate through all users in the Firebase project starting from this page.

get_next_page()

Retrieves the next page of user accounts, if available.

Returns:Next page of users, or None if this is the last page.
Return type:ListUsersPage
iterate_all()

Retrieves an iterator for user accounts.

Returned iterator will iterate through all the user accounts in the Firebase project starting from this page. The iterator will never buffer more than one page of users in memory at a time.

Returns:An iterator of ExportedUserRecord instances.
Return type:iterator
has_next_page

A boolean indicating whether more pages are available.

next_page_token

Page token string for the next page (empty string indicates no more pages).

users

A list of ExportedUserRecord instances available in this page.

class firebase_admin.auth.UserImportHash(name, data=None)

Bases: object

Represents a hash algorithm used to hash user passwords.

An instance of this class must be specified when importing users with passwords via the auth.import_users() API. Use one of the provided class methods to obtain new instances when required. Refer to documentation for more details.

classmethod bcrypt()

Creates a new Bcrypt algorithm instance.

Returns:A new UserImportHash.
Return type:UserImportHash
classmethod hmac_md5(key)

Creates a new HMAC MD5 algorithm instance.

Parameters:key – Signer key as a byte sequence.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod hmac_sha1(key)

Creates a new HMAC SHA1 algorithm instance.

Parameters:key – Signer key as a byte sequence.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod hmac_sha256(key)

Creates a new HMAC SHA256 algorithm instance.

Parameters:key – Signer key as a byte sequence.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod hmac_sha512(key)

Creates a new HMAC SHA512 algorithm instance.

Parameters:key – Signer key as a byte sequence.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod md5(rounds)

Creates a new MD5 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod pbkdf_sha1(rounds)

Creates a new PBKDF SHA1 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod pbkdf_sha256(rounds)

Creates a new PBKDF2 SHA256 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod scrypt(key, rounds, memory_cost, salt_separator=None)

Creates a new Scrypt algorithm instance.

This is the modified Scrypt algorithm used by Firebase Auth. See standard_scrypt() function for the standard Scrypt algorith,

Parameters:
  • key – Signer key as a byte sequence.
  • rounds – Number of rounds. Must be an integer between 1 and 8.
  • memory_cost – Memory cost as an integer between 1 and 14.
  • salt_separator – Salt separator as a byte sequence (optional).
Returns:

A new UserImportHash.

Return type:

UserImportHash

classmethod sha1(rounds)

Creates a new SHA1 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod sha256(rounds)

Creates a new SHA256 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod sha512(rounds)

Creates a new SHA512 algorithm instance.

Parameters:rounds – Number of rounds. Must be an integer between 0 and 120000.
Returns:A new UserImportHash.
Return type:UserImportHash
classmethod standard_scrypt(memory_cost, parallelization, block_size, derived_key_length)

Creates a new standard Scrypt algorithm instance.

Parameters:
  • memory_cost – Memory cost as a non-negaive integer.
  • parallelization – Parallelization as a non-negative integer.
  • block_size – Block size as a non-negative integer.
  • derived_key_length – Derived key length as a non-negative integer.
Returns:

A new UserImportHash.

Return type:

UserImportHash

to_dict()
class firebase_admin.auth.UserImportResult(result, total)

Bases: object

Represents the result of a bulk user import operation.

See auth.import_users() API for more details.

errors

Returns a list of auth.ErrorInfo instances describing the errors encountered.

failure_count

Returns the number of users that failed to be imported.

success_count

Returns the number of users successfully imported.

class firebase_admin.auth.UserInfo

Bases: object

A collection of standard profile information for a user.

Used to expose profile information returned by an identity provider.

display_name

Returns the display name of this user.

email

Returns the email address associated with this user.

phone_number

Returns the phone number associated with this user.

photo_url

Returns the photo URL of this user.

provider_id

Returns the ID of the identity provider.

This can be a short domain name (e.g. google.com), or the identity of an OpenID identity provider.

uid

Returns the user ID of this user.

class firebase_admin.auth.UserMetadata(creation_timestamp=None, last_sign_in_timestamp=None)

Bases: object

Contains additional metadata associated with a user account.

creation_timestamp

Creation timestamp in milliseconds since the epoch.

Returns:The user creation timestamp in milliseconds since the epoch.
Return type:integer
last_sign_in_timestamp

Last sign in timestamp in milliseconds since the epoch.

Returns:The last sign in timestamp in milliseconds since the epoch.
Return type:integer
class firebase_admin.auth.UserProvider(uid, provider_id, email=None, display_name=None, photo_url=None)

Bases: object

Represents a user identity provider that can be associated with a Firebase user.

One or more providers can be specified in an ImportUserRecord when importing users via auth.import_users().

Parameters:
  • uid – User’s unique ID assigned by the identity provider.
  • provider_id – ID of the identity provider. This can be a short domain name or the identifier of an OpenID identity provider.
  • email – User’s email address (optional).
  • display_name – User’s display name (optional).
  • photo_url – User’s photo URL (optional).
to_dict()
display_name
email
photo_url
provider_id
uid
class firebase_admin.auth.UserRecord(data)

Bases: firebase_admin._user_mgt.UserInfo

Contains metadata associated with a Firebase user account.

custom_claims

Returns any custom claims set on this user account.

Returns:A dictionary of claims or None.
Return type:dict
disabled

Returns whether this user account is disabled.

Returns:True if the user account is disabled, and False otherwise.
Return type:bool
display_name

Returns the display name of this user.

Returns:A display name string or None.
Return type:string
email

Returns the email address associated with this user.

Returns:An email address string or None.
Return type:string
email_verified

Returns whether the email address of this user has been verified.

Returns:True if the email has been verified, and False otherwise.
Return type:bool
phone_number

Returns the phone number associated with this user.

Returns:A phone number string or None.
Return type:string
photo_url

Returns the photo URL of this user.

Returns:A URL string or None.
Return type:string
provider_data

Returns a list of UserInfo instances.

Each object represents an identity from an identity provider that is linked to this user.

Returns:A list of UserInfo objects, which may be empty.
Return type:list
provider_id

Returns the provider ID of this user.

Returns:A constant provider ID value.
Return type:string
tokens_valid_after_timestamp

Returns the time, in milliseconds since the epoch, before which tokens are invalid.

Note: this is truncated to 1 second accuracy.

Returns:
Timestamp in milliseconds since the epoch, truncated to the second.
All tokens issued before that time are considered revoked.
Return type:int
uid

Returns the user ID of this user.

Returns:A user ID string. This value is never None or empty.
Return type:string
user_metadata

Returns additional metadata associated with this user.

Returns:A UserMetadata instance. Does not return None.
Return type:UserMetadata

Functions

firebase_admin.auth.create_custom_token(uid, developer_claims=None, app=None)

Builds and signs a Firebase custom auth token.

Parameters:
  • uid – ID of the user for whom the token is created.
  • developer_claims – A dictionary of claims to be included in the token (optional).
  • app – An App instance (optional).
Returns:

A token minted from the input parameters.

Return type:

bytes

Raises:

ValueError – If input parameters are invalid.

firebase_admin.auth.create_session_cookie(id_token, expires_in, app=None)

Creates a new Firebase session cookie from the given ID token and options.

The returned JWT can be set as a server-side session cookie with a custom cookie policy.

Parameters:
  • id_token – The Firebase ID token to exchange for a session cookie.
  • expires_in – Duration until the cookie is expired. This can be specified as a numeric seconds value or a datetime.timedelta instance.
  • app – An App instance (optional).
Returns:

A session cookie generated from the input parameters.

Return type:

bytes

Raises:
  • ValueError – If input parameters are invalid.
  • AuthError – If an error occurs while creating the cookie.
firebase_admin.auth.create_user(**kwargs)

Creates a new user account with the specified properties.

Keyword Arguments:
 
  • uid – User ID to assign to the newly created user (optional).
  • display_name – The user’s display name (optional).
  • email – The user’s primary email (optional).
  • email_verified – A boolean indicating whether or not the user’s primary email is verified (optional).
  • phone_number – The user’s primary phone number (optional).
  • photo_url – The user’s photo URL (optional).
  • password – The user’s raw, unhashed password. (optional).
  • disabled – A boolean indicating whether or not the user account is disabled (optional).
  • app – An App instance (optional).
Returns:

A UserRecord instance for the newly created user.

Return type:

UserRecord

Raises:
  • ValueError – If the specified user properties are invalid.
  • AuthError – If an error occurs while creating the user account.
firebase_admin.auth.delete_user(uid, app=None)

Deletes the user identified by the specified user ID.

Parameters:
  • uid – A user ID string.
  • app – An App instance (optional).
Raises:
  • ValueError – If the user ID is None, empty or malformed.
  • AuthError – If an error occurs while deleting the user account.
firebase_admin.auth.get_user(uid, app=None)

Gets the user data corresponding to the specified user ID.

Parameters:
  • uid – A user ID string.
  • app – An App instance (optional).
Returns:

A UserRecord instance.

Return type:

UserRecord

Raises:
  • ValueError – If the user ID is None, empty or malformed.
  • AuthError – If an error occurs while retrieving the user or if the specified user ID does not exist.
firebase_admin.auth.get_user_by_email(email, app=None)

Gets the user data corresponding to the specified user email.

Parameters:
  • email – A user email address string.
  • app – An App instance (optional).
Returns:

A UserRecord instance.

Return type:

UserRecord

Raises:
  • ValueError – If the email is None, empty or malformed.
  • AuthError – If an error occurs while retrieving the user or no user exists by the specified email address.
firebase_admin.auth.get_user_by_phone_number(phone_number, app=None)

Gets the user data corresponding to the specified phone number.

Parameters:
  • phone_number – A phone number string.
  • app – An App instance (optional).
Returns:

A UserRecord instance.

Return type:

UserRecord

Raises:
  • ValueError – If the phone number is None, empty or malformed.
  • AuthError – If an error occurs while retrieving the user or no user exists by the specified phone number.
firebase_admin.auth.import_users(users, hash_alg=None, app=None)

Imports the specified list of users into Firebase Auth.

At most 1000 users can be imported at a time. This operation is optimized for bulk imports and will ignore checks on identifier uniqueness which could result in duplications. The hash_alg parameter must be specified when importing users with passwords. Refer to the UserImportHash class for supported hash algorithms.

Parameters:
  • users – A list of ImportUserRecord instances to import. Length of the list must not exceed 1000.
  • hash_alg – A UserImportHash object (optional). Required when importing users with passwords.
  • app – An App instance (optional).
Returns:

An object summarizing the result of the import operation.

Return type:

UserImportResult

Raises:
  • ValueError – If the provided arguments are invalid.
  • AuthError – If an error occurs while importing users.
firebase_admin.auth.list_users(page_token=None, max_results=1000, app=None)

Retrieves a page of user accounts from a Firebase project.

The page_token argument governs the starting point of the page. The max_results argument governs the maximum number of user accounts that may be included in the returned page. This function never returns None. If there are no user accounts in the Firebase project, this returns an empty page.

Parameters:
  • page_token – A non-empty page token string, which indicates the starting point of the page (optional). Defaults to None, which will retrieve the first page of users.
  • max_results – A positive integer indicating the maximum number of users to include in the returned page (optional). Defaults to 1000, which is also the maximum number allowed.
  • app – An App instance (optional).
Returns:

A ListUsersPage instance.

Return type:

ListUsersPage

Raises:
  • ValueError – If max_results or page_token are invalid.
  • AuthError – If an error occurs while retrieving the user accounts.
firebase_admin.auth.revoke_refresh_tokens(uid, app=None)

Revokes all refresh tokens for an existing user.

revoke_refresh_tokens updates the user’s tokens_valid_after_timestamp to the current UTC in seconds since the epoch. It is important that the server on which this is called has its clock set correctly and synchronized.

While this revokes all sessions for a specified user and disables any new ID tokens for existing sessions from getting minted, existing ID tokens may remain active until their natural expiration (one hour). To verify that ID tokens are revoked, use verify_id_token(idToken, check_revoked=True).

firebase_admin.auth.set_custom_user_claims(uid, custom_claims, app=None)

Sets additional claims on an existing user account.

Custom claims set via this function can be used to define user roles and privilege levels. These claims propagate to all the devices where the user is already signed in (after token expiration or when token refresh is forced), and next time the user signs in. The claims can be accessed via the user’s ID token JWT. If a reserved OIDC claim is specified (sub, iat, iss, etc), an error is thrown. Claims payload must also not be larger then 1000 characters when serialized into a JSON string.

Parameters:
  • uid – A user ID string.
  • custom_claims – A dictionary or a JSON string of custom claims. Pass None to unset any claims set previously.
  • app – An App instance (optional).
Raises:
  • ValueError – If the specified user ID or the custom claims are invalid.
  • AuthError – If an error occurs while updating the user account.
firebase_admin.auth.update_user(uid, **kwargs)

Updates an existing user account with the specified properties.

Parameters:
  • uid – A user ID string.
  • kwargs – A series of keyword arguments (optional).
Keyword Arguments:
 
  • display_name – The user’s display name (optional). Can be removed by explicitly passing None.
  • email – The user’s primary email (optional).
  • email_verified – A boolean indicating whether or not the user’s primary email is verified (optional).
  • phone_number – The user’s primary phone number (optional). Can be removed by explicitly passing None.
  • photo_url – The user’s photo URL (optional). Can be removed by explicitly passing None.
  • password – The user’s raw, unhashed password. (optional).
  • disabled – A boolean indicating whether or not the user account is disabled (optional).
  • custom_claims – A dictionary or a JSON string contining the custom claims to be set on the user account (optional).
  • valid_since – An integer signifying the seconds since the epoch. This field is set by revoke_refresh_tokens and it is discouraged to set this field directly.
Returns:

An updated UserRecord instance for the user.

Return type:

UserRecord

Raises:
  • ValueError – If the specified user ID or properties are invalid.
  • AuthError – If an error occurs while updating the user account.
firebase_admin.auth.verify_id_token(id_token, app=None, check_revoked=False)

Verifies the signature and data for the provided JWT.

Accepts a signed token string, verifies that it is current, and issued to this project, and that it was correctly signed by Google.

Parameters:
  • id_token – A string of the encoded JWT.
  • app – An App instance (optional).
  • check_revoked – Boolean, If true, checks whether the token has been revoked (optional).
Returns:

A dictionary of key-value pairs parsed from the decoded JWT.

Return type:

dict

Raises:
  • ValueError – If the JWT was found to be invalid, or if the App’s project ID cannot be determined.
  • AuthError – If check_revoked is requested and the token was revoked.
firebase_admin.auth.verify_session_cookie(session_cookie, check_revoked=False, app=None)

Verifies a Firebase session cookie.

Accepts a session cookie string, verifies that it is current, and issued to this project, and that it was correctly signed by Google.

Parameters:
  • session_cookie – A session cookie string to verify.
  • check_revoked – Boolean, if true, checks whether the cookie has been revoked (optional).
  • app – An App instance (optional).
Returns:

A dictionary of key-value pairs parsed from the decoded JWT.

Return type:

dict

Raises:
  • ValueError – If the cookie was found to be invalid, or if the App’s project ID cannot be determined.
  • AuthError – If check_revoked is requested and the cookie was revoked.

Send feedback about...

Need help? Visit our support page.