JavaScript Web Guide

Custom Authentication

Firebase apps give you complete control over user authentication by allowing you to authenticate users
using secure JSON Web Tokens (JWTs). This method of authentication is useful in cases where you
are already managing user accounts on your server, where you have more advanced authentication
needs, or for authenticating server-side workers.

Generating a Secure Token

To authenticate a user with Custom Login, we must provide each client with a secure JWT that
has been generated on a server. There are several
helper libraries for generating JWTs given a Firebase app's secret. Our secret can be found
under the Secrets tab in our Firebase app's dashboard.

Firebase JWTs should always be generated on a trusted server so that the Firebase app secret
which is needed to generate them can be kept private. Here are some examples of generating JWTs
on a server using several different languages:

When authenticating with a secure JWT, the data encoded in the token will be accessible in the
Security and Firebase Rules as the auth
variable. This allows rules to be written which grant access based on the data within the token.

Token Restrictions

The token payload can contain any data of your choosing with the restriction that it must
contain a uid key that is a string of less than 256 characters. The generated
token's total payload must also be less than 1024 characters.

By default, authentication tokens expire 24 hours after they are issued and the client will
automatically be unauthenticated at that time. You can override this by changing the session
length setting under the Login & Auth tab of your App Dashboard,
or individually when creating the token by providing a specific expiration date. For details,
see the docs for the specific token generator
library you're using.

To handle token expiration gracefully, we can use the
onAuth() method, which triggers
the provided callback whenever the authentication state changes.

Authenticating Clients

Once we've generated a secure JWT, we can use it to authenticate any Firebase database
reference:

Calling an authentication method on any Firebase database reference will authenticate all
references. If our app loses its Internet connection, Firebase clients will automatically
handle re-authenticating to the server when it reconnects. If we need to change a
client's credentials (for example, when a user logs in to a different account), simply
re-authenticate with a new token.

Optional Settings

authWithCustomToken() takes an optional third parameter which is an object containing any of the following settings:

Name

Description

Type

remember

If not specified - or set to default - sessions are persisted for as long as you have configured in the Login & Auth tab of your Firebase's Dashboard. To limit persistence to the lifetime of the current window, set this to sessionOnly. A value of none will not persist authentication data at all and will end authentication as soon as the page is closed.

String

Here is an example of custom login where the session will expire upon browser shutdown:

It is not possible to authenticate with multiple credentials to the same Firebase database
simultaneously, even if we call authWithCustomToken() on different references.
Authentication state is global and applies to all references to the Firebase database. However,
it is possible to create references to two or more different Firebase databases and
authenticate to those independently.

authData Object

Field

Description

Type

auth

The contents of the authentication token, which will be available as the
auth variable within your
Security and Firebase Rules.

Object

expires

A timestamp, in seconds since the UNIX epoch, indicating when the authentication token
expires.

Number

provider

The authentication method used, in this case: custom.

String

token

The Firebase authentication token for this session.

String

uid

A unique user ID, intended as the user's unique key across all providers.

String

To unauthenticate a client, use the unauth method:

ref.unauth();

[ref unauth];

ref.unauth()

ref.unauth();

Authenticating Servers

If we are running a trusted server that is connecting to our Firebase database, we can
authenticate it in several ways:

Using a Firebase app secret: All authentication methods can accept a Firebase
app secret instead of a JWT token. This will grant the server complete read and write access
to the entire Firebase database. This access will never expire unless it is revoked via the
App Dashboard.

Using a secure JWT with the optional admin claim set to true:
This method will grant a server complete read and write access to the entire Firebase database.
This token will expire normally, so it is important to set the expiration times accordingly.

Using a secure JWT designed to give access to only the pieces of data a server needs
to touch: This method is more complicated, but it is the safest way to authenticate a
server as it lets the Security and Firebase
Rules prevent the server from doing anything it's not supposed to, even if it becomes
compromised in some way.

Generating a Token Without a Helper Library

Firebase app JWTs can also be generated with any existing JWT generation library and then signed by
a SHA-256 HMAC signature. When using an existing library, a Firebase app auth token must
contain the following claims:

Claim

Description

v

The version of the token. Set this to the number 0.

iat

The "issued at" date as a number of seconds since the Unix epoch.

d

The authentication data. This is the payload of the token that will become visible as the
auth variable in the Security and Firebase Rules.

The following claims are optional when using an authentication token:

Claim

Description

nbf

The token "not before" date as a number of seconds since the Unix epoch. If specified, the
token will not be considered valid until after this date.

exp

The token expiration date as a number of seconds since the Unix epoch. If not specified, by
default the token will expire 24 hours after the "issued at" date (iat).

admin

Set to true to make this an "admin" token, which grants full read and write
access to all data.

debug

Set to true to enable debug mode, which provides verbose error messages when
Security and Firebase Rules fail.