Create Custom Tokens  |  Firebase Authentication (2022)

Firebase gives you complete control over authentication by allowing you toauthenticate users or devices using secure JSON Web Tokens (JWTs). You generatethese tokens on your server, pass them back to a client device, and then usethem to authenticate via the signInWithCustomToken() method.

To achieve this, you must create a server endpoint that accepts sign-incredentials—such as a username and password—and, if the credentials arevalid, returns a custom JWT. The custom JWT returned from your server can thenbe used by a client device to authenticate with Firebase(iOS+, Android,web). Once authenticated, this identity will beused when accessing other Firebase services, such as the Firebase Realtime Databaseand Cloud Storage. Furthermore, the contents of the JWT will beavailable in the auth object in yourRealtime Database Rules and therequest.auth object in yourCloud Storage Security Rules.

You can create a custom token with the Firebase Admin SDK, or you canuse a third-party JWT library if your server is written ina language which Firebase does not natively support.

Before you begin

Custom tokens are signed JWTs where the private key used for signing belongs toa Google service account. There are several ways to specify the Google serviceaccount that should be used by the Firebase Admin SDK for signing customtokens:

  • Using a service account JSON file --This method can be used in anyenvironment, but requires you to package a service account JSON filealong with your code. Special care must be taken to ensure that theservice account JSON file is not exposed to external parties.
  • Letting the Admin SDK discover a service account-- This methodcan be used in environments managed by Google such as Google CloudFunctions and App Engine. You may have to configure someadditional permissions via the Google Cloud Console.
  • Using a service account ID --When used in a Google-managed environment this method will sign tokens usingthe specified service account's key.However, it uses a remote web service, and you may have to configureadditional permissions for this service account via theGoogle Cloud Console.

Using a service account JSON file

Service account JSON files contain all the information corresponding to serviceaccounts (including the RSA private key). They can be downloaded from theFirebase console. Follow the Admin SDK set upinstructions for more information on how toinitialize the Admin SDK with a service account JSON file.

This method of initialization is suitable for a wide range of Admin SDKdeployments. Also it enables the Admin SDK to create and sign custom tokenslocally, without making any remote API calls. The main drawback of thisapproach is that it requires you to package a service account JSON filealong with your code. Also note that the private key in a service accountJSON file is sensitive information, and special care must be taken to keepit confidential. Specifically, refrain from adding service account JSON filesto public version control.

Letting the Admin SDK discover a service account

If your code is deployed in an environment managed by Google, the Admin SDKcan attempt to auto-discover a means to sign custom tokens:

  • If your code is deployed in the App Engine standard environment forJava, Python or Go, the Admin SDK can use theApp Identity servicepresent in that environment to sign custom tokens. The App Identity servicesigns data using a service account provisioned for your app by Google AppEngine.

  • If your code is deployed in some other managed environment (e.g. Google CloudFunctions, Google Compute Engine), the Firebase Admin SDK can auto-discover aservice account ID string from the localmetadata server.The discovered service account ID is then used in conjunction with the IAMservice to sign tokens remotely.

To make use of these signing methods, initialize the SDK with GoogleApplication Default credentials and do not specify a service account ID string:






default_app = firebase_admin.initialize_app()


app, err := firebase.NewApp(context.Background(), nil)if err != nil {log.Fatalf("error initializing app: %v\n", err)}


(Video) Minting Custom Tokens with the Admin SDK for Node.js - Firecasts



To test the same code locally, download a service account JSON file and set theGOOGLE_APPLICATION_CREDENTIALS environment variable to point to it.

If the Firebase Admin SDK has to discover a service account ID string, it doesso when your code creates a custom token for the first time.The result is cached and reused for subsequent token signing operations.The auto-discovered service account ID is usually one of the default serviceaccounts provided by the Google Cloud:

  • Default Compute Engine service account
  • Default Cloud Functions service account

Just like with explicitly specified service account IDs, auto-discoverd serviceaccount IDs must have the iam.serviceAccounts.signBlob permission for thecustom token creation to work. You may have to use theIAM and admin sectionof the Google Cloud Console to grant the default service accounts thenecessary permissions. See the troubleshooting section below for more details.

Using a service account ID

To maintain consistency between various parts of your application, you canspecify a service account ID whose keys will be used to sign tokens when runningin a Google-managed environment.This can make IAM policies simpler and more secure, and avoid having toinclude the service account JSON file in your code.

The service account ID can be found in theGoogle Cloud Console,or in the client_email field of a downloaded service account JSON file.Service account IDs are email addresses that have the following format:<client-id>@<project-id> They uniquely identifyservice accounts in Firebase and Google Cloud projects.

To create custom tokens using a separate service account ID, initialize the SDKas shown below:


initializeApp({ serviceAccountId: '',});


FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) .setServiceAccountId("") .build();FirebaseApp.initializeApp(options);


options = { 'serviceAccountId': '',}firebase_admin.initialize_app(options=options)


conf := &firebase.Config{ServiceAccountID: "",}app, err := firebase.NewApp(context.Background(), conf)if err != nil {log.Fatalf("error initializing app: %v\n", err)}


FirebaseApp.Create(new AppOptions(){ Credential = GoogleCredential.GetApplicationDefault(), ServiceAccountId = "",});

Service account IDs are not sensitive information and therefore their exposureis inconsequential. However, to sign custom tokens with the specified serviceaccount, the Firebase Admin SDK must invoke a remote service.Moreover, you must also make sure that the service account the Admin SDK isusing to make this call—usually {project-name}—has the iam.serviceAccounts.signBlobpermission.See the troubleshooting section below for more details.

Create custom tokens using the Firebase Admin SDK

The Firebase Admin SDK has a built-in method for creating custom tokens. Ata minimum, you need to provide a uid, which can be any string but shoulduniquely identify the user or device you are authenticating. These tokens expireafter one hour.

(Video) Minting Custom Tokens with the Admin SDK for Java - Firecasts


const uid = 'some-uid';getAuth() .createCustomToken(uid) .then((customToken) => { // Send token back to client }) .catch((error) => { console.log('Error creating custom token:', error); });


String uid = "some-uid";String customToken = FirebaseAuth.getInstance().createCustomToken(uid);// Send token back to client


uid = 'some-uid'custom_token = auth.create_custom_token(uid)


client, err := app.Auth(context.Background())if err != nil {log.Fatalf("error getting Auth client: %v\n", err)}token, err := client.CustomToken(ctx, "some-uid")if err != nil {log.Fatalf("error minting custom token: %v\n", err)}log.Printf("Got custom token: %v\n", token)


var uid = "some-uid";string customToken = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid);// Send token back to client

You can also optionally specify additional claims to be included in the customtoken. For example, below, a premiumAccount field has been added to thecustom token, which will be available in the auth / request.auth objectsin your Security Rules:


const userId = 'some-uid';const additionalClaims = { premiumAccount: true,};getAuth() .createCustomToken(userId, additionalClaims) .then((customToken) => { // Send token back to client }) .catch((error) => { console.log('Error creating custom token:', error); });


String uid = "some-uid";Map<String, Object> additionalClaims = new HashMap<String, Object>();additionalClaims.put("premiumAccount", true);String customToken = FirebaseAuth.getInstance() .createCustomToken(uid, additionalClaims);// Send token back to client


uid = 'some-uid'additional_claims = { 'premiumAccount': True}custom_token = auth.create_custom_token(uid, additional_claims)


client, err := app.Auth(context.Background())if err != nil {log.Fatalf("error getting Auth client: %v\n", err)}claims := map[string]interface{}{"premiumAccount": true,}token, err := client.CustomTokenWithClaims(ctx, "some-uid", claims)if err != nil {log.Fatalf("error minting custom token: %v\n", err)}log.Printf("Got custom token: %v\n", token)


var uid = "some-uid";var additionalClaims = new Dictionary<string, object>(){ { "premiumAccount", true },};string customToken = await FirebaseAuth.DefaultInstance .CreateCustomTokenAsync(uid, additionalClaims);// Send token back to client

Reserved custom token names

Sign in using custom tokens on clients

After you create a custom token, you should send it to your client app. Theclient app authenticates with the custom token by callingsignInWithCustomToken():

(Video) Minting Custom Tokens with the Admin SDK for Python - Firecasts


[[FIRAuth auth] signInWithCustomToken:customToken completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { // ...}];
Auth.auth().signIn(withCustomToken: customToken ?? "") { user, error in // ...}


mAuth.signInWithCustomToken(mCustomToken) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCustomToken:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCustomToken:failure", task.getException()); Toast.makeText(CustomAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });


auth.SignInWithCustomTokenAsync(custom_token).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithCustomTokenAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithCustomTokenAsync encountered an error: " + task.Exception); return; } Firebase.Auth.FirebaseUser newUser = task.Result; Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);});


firebase::Future<firebase::auth::User*> result = auth->SignInWithCustomToken(custom_token);

Web version 8

firebase.auth().signInWithCustomToken(token) .then((userCredential) => { // Signed in var user = userCredential.user; // ... }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; // ... });

Web version 9

import { getAuth, signInWithCustomToken } from "firebase/auth";const auth = getAuth();signInWithCustomToken(auth, token) .then((userCredential) => { // Signed in const user = userCredential.user; // ... }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; // ... });

If the authentication succeeds, your user will be now signed in into yourclient app with the account specified by the uid included in the customtoken. If that account did not previously exist, a record for that user will becreated.

In the same way as with other sign-in methods (such assignInWithEmailAndPassword() and signInWithCredential()) the auth objectin your Realtime Database Rules andthe request.auth object in yourCloud Storage Security Rules will bepopulated with the user's uid. In this case, the uid will be the one thatyou specified when generating the custom token.

Database Rules

{ "rules": { "adminContent": { ".read": "auth.uid === 'some-uid'" } }}

Storage Rules

service { match /b/<your-firebase-storage-bucket>/o { match /adminContent/{filename} { allow read, write: if request.auth != null && request.auth.uid == "some-uid"; } }}

If the custom token contains additional claims, they can be referenced off ofthe auth.token (Firebase Realtime Database) or request.auth.token(Cloud Storage) object in your rules:

Database Rules

{ "rules": { "premiumContent": { ".read": "auth.token.premiumAccount === true" } }}

Storage Rules

service { match /b/<your-firebase-storage-bucket>/o { match /premiumContent/{filename} { allow read, write: if request.auth.token.premiumAccount == true; } }}

Create custom tokens using a third-party JWT library

If your backend is in a language that doesn't have an official Firebase AdminSDK, you can still manually create custom tokens. First,find a third-party JWT library for your language. Then, usethat JWT library to mint a JWT which includes the following claims:

Custom Token Claims
alg Algorithm "RS256"
iss Issuer Your project's service account email address
sub Subject Your project's service account email address
aud Audience ""
iat Issued-at time The current time, in seconds since the UNIX epoch
exp Expiration time The time, in seconds since the UNIX epoch, at which the token expires. It can be a maximum of 3600 seconds later than the iat.
Note: this only controls the time when the custom token itself expires. But once you sign a user in using signInWithCustomToken(), they will remain signed in into the device until their session is invalidated or the user signs out.
uid The unique identifier of the signed-in user must be a string, between 1-36 characters long
claims (optional) Optional custom claims to include in the Security Rules auth / request.auth variables

Here are some example implementations of how to create custom tokens in avariety of languages that the Firebase Admin SDK does not support:

(Video) Minting Custom Tokens with the Admin SDK for Go - Firecasts


Using php-jwt:

// Requires: composer require firebase/php-jwtuse Firebase\JWT\JWT;// Get your service account's email address and private key from the JSON key file$service_account_email = "";$private_key = "-----BEGIN PRIVATE KEY-----...";function create_custom_token($uid, $is_premium_account) { global $service_account_email, $private_key; $now_seconds = time(); $payload = array( "iss" => $service_account_email, "sub" => $service_account_email, "aud" => "", "iat" => $now_seconds, "exp" => $now_seconds+(60*60), // Maximum expiration time is one hour "uid" => $uid, "claims" => array( "premium_account" => $is_premium_account ) ); return JWT::encode($payload, $private_key, "RS256");}


Using ruby-jwt:

require "jwt"# Get your service account's email address and private key from the JSON key file$service_account_email = ""$private_key = "-----BEGIN PRIVATE KEY-----\n..."def create_custom_token(uid, is_premium_account) now_seconds = payload = {:iss => $service_account_email, :sub => $service_account_email, :aud => "", :iat => now_seconds, :exp => now_seconds+(60*60), # Maximum expiration time is one hour :uid => uid, :claims => {:premium_account => is_premium_account}} JWT.encode payload, $private_key, "RS256"end

After you create the custom token, send it to your client app to use toauthenticate with Firebase. See the code samples above for how to do this.


This section outlines some common problems developers may encounter whencreating custom tokens, and how to resolve them.

IAM API not enabled

If you are specifying a service account ID for signing tokens you may getan error similar to the following:

Identity and Access Management (IAM) API has not been used in project1234567890 before or it is disabled. Enable it by visiting retry. If you enabled this API recently, wait a few minutes for the actionto propagate to our systems and retry.

The Firebase Admin SDK uses theIAM APIto sign tokens. This error indicates that the IAM API is not currently enabledfor yourFirebase project. Open the link in the error message in a web browser, andclick the "Enable API" button to enable it for your project.

Service account does not have required permissions

If the service account the Firebase Admin SDK is running as does not have theiam.serviceAccounts.signBlob permission, you may get an error message likethe following:

Permission iam.serviceAccounts.signBlob is required to perform this operationon service account projects/-/serviceAccounts/{your-service-account-id}.

The easiest way to resolve this is to grant the "Service Account Token Creator"IAM role to the service account in question, usually{project-name}

  1. Open the IAM and adminpage in the Google Cloud Console.
  2. Select your project and click "Continue".
  3. Click the edit icon corresponding to the service account you wish to update.
  4. Click on "Add Another Role".
  5. Type "Service Account Token Creator" into the search filter, and selectit from the results.
  6. Click "Save" to confirm the role grant.

Refer to IAM documentationfor more details on this process, or learn how to do update roles using thegcloud command-line tools.

Failed to determine service account

If you get an error message similar to the following, the Firebase Admin SDKhas not been properly initialized.

Failed to determine service account ID. Initialize the SDK with service accountcredentials or specify a service account ID with iam.serviceAccounts.signBlobpermission.

If you are relying on the SDK to auto-discover a service account ID, make surethe code is deployed in a managed Google environment with a metadata server.Otherwise, be sure to specify service account JSON file or service account IDat the SDK initialization.

(Video) Firebase Authentication: From fully managed to fully customizable


Create Custom Tokens  |  Firebase Authentication? ›

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.

What is custom token authentication? ›

What Are Custom Authentication Tokens? An authentication token is some data, represented as a string or XML, that identifies an entity (user or process), such as an X509 client certificate. Typically, authentication tokens are designed to be used within specific security protocols.

How do I get custom tokens? ›

How to add custom token in Trust wallet - YouTube

How do you use signInWithCustomToken? ›

initializeApp(adminConfig, 'admin'); var token = adminApp. auth(). createCustomToken('12345678', { customField: 'customValue' }); Then on the client try to signInWithCustomToken(token) Make sure the client is using the same api key that belongs to the same project where the service account was generated.

Do firebase tokens expire? ›

Firebase ID tokens are short lived and last for an hour; the refresh token can be used to retrieve new ID tokens. Refresh tokens expire only when one of the following occurs: The user is deleted. The user is disabled.

How do I create a custom token on my trust wallet? ›

Open the Trust Wallet app and search for the token in the search bar. Tap “Add Custom Token” in the right top corner. Select the appropriate network and paste the token address in the designated box. Enter the details of the token, including its name, then press “Save.”

How do I make a crypto token? ›

You can create either a crypto coin or a token. There can be only one coin per blockchain, and you make it when building a new blockchain.
How to Create a Crypto Token in 4 Steps
  1. Step 1: Define your token properties. ...
  2. Step 2: Develop a smart contract. ...
  3. Step 3: Run QA on a test chain. ...
  4. Step 4: Deploy to blockchain.
Jun 13, 2022

How do I add custom tokens to MetaMask? ›

Adding Custom Tokens to MetaMask Wallet from Etherscan
  1. Open your in-app browser.
  2. Go to Etherscan.
  3. Search for your custom token.
  4. Scroll down and retrieve the token's contract address.
  5. Go back to your wallet.
  6. Select “Add Token” MetaMask automatically updates the “token symbol” and “tokens of precision”
  7. Viola!

How do I add a custom token to Pancakeswap? ›

You just need to press button “add token” from the bottom and then choose either: search token. Custom token.
All you need to do is just pick 3 things from overview and profile summary:
  1. Token contract address.
  2. Token symbol.
  3. Decimals of precision.

How do I add a custom token to Coinbase wallet? ›

Go to the Coinbase Wallet extension, click Show Wallet address > QR code. Open the Trust Wallet mobile app, and tap Send > QR code and scan the Coinbase Wallet extension QR code in your web browser. Enter the amount of crypto you'd like to send and select the asset.

How can I get FCM token? ›

  1. On this page.
  2. Set up the SDK.
  3. Edit your app manifest.
  4. Request runtime notification permission on Android 13+ Notification permissions for apps targeting Android 12L (API level 32) or lower. ...
  5. Access the device registration token. ...
  6. Check for Google Play services.
  7. Prevent auto initialization.
  8. Next steps.

How do I decode a token? ›

Decode JWT Token and Verify in Plain Java
  1. Struture of the JWT Token. A JWT Token looks as follows. ...
  2. Split the JWT Token. The token received in the request must contain 3 parts we mentioned above. ...
  3. Base64 Decode. ...
  4. Parse the JSON. ...
  5. Check the Expiry Timestamp. ...
  6. Verify the Signature. ...
  7. Access User information from Payload. ...
  8. Reference.
Oct 2, 2021

Is firebase Auth JWT? ›

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.

Where are Firebase tokens stored? ›

Token can be found in firebaseLocalStorageDB.

How long do FCM tokens last? ›

Ensuring registration token freshness

To cover all cases, you should adopt a threshold for when you consider tokens stale; our recommendation is two months. Any token older than two months is likely to be an inactive device; an active device would have otherwise refreshed its token.

How do I use authentication token in REST API? ›

  1. Step 1: Create authorization request link.
  2. Step 2: Request user for authorization.
  3. Step 3: Exchange authorization code with access tokenpost.
  4. Step 4: Use access token for REST API requests.
  5. Step 5: Get new access token using refresh token.

What are the different types of authentication tokens? ›

The most common types of tokens are key fobs and USB or wireless tokens. Hardware tokens can be divided into three categories. Contactless—a contactless token doesn't require you to enter an access code or connect to a device.

What is custom authentication in ASP NET? ›

For building custom authentication, we use membership provider class which is able to check the user credentials (username & password) and role provider class that is used to verify the user authorization based on his/her roles.

What does use token mean on Chase? ›

Security Token Code. Secure tokens are provided to users when they require additional security. Do not select this option or enter data in the "Token" field unless instructed to do so; your User ID may become locked.

How do I get my discord server token? ›

How to get a Bot Token
  1. Go to Discord developer portal.
  2. Open your Application's settings.
  3. Navigate to the Bot section on the left.
  4. Under Token click Copy.
Mar 24, 2022


1. Firebase Auth Tutorial #17 - Intro to Custom Claims
(The Net Ninja)
2. Controlling Data Access Using Firebase Auth Custom Claims (Firecasts)
3. Spring boot service to Create Firebase Custom Token
(WJ Prajumsook)
4. Flutter & Firebase App Tutorial #6 - Custom User Model
(The Net Ninja)
5. JWT Authentication Tutorial - Node.js
(Web Dev Simplified)
6. Firebase Auth Tutorial #15- Firestore Users Collection
(The Net Ninja)

Top Articles

Latest Posts

Article information

Author: Reed Wilderman

Last Updated: 09/10/2022

Views: 5623

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.