Creating custom tokens  |  Identity Platform Documentation  |  Google Cloud (2024)

This document shows you how to use Identity Platform to create custom JSON WebTokens (JWTs).

Custom tokens give you complete control over the authentication process. Yougenerate these tokens on your server, pass them back to a client device, andthen call signInWithCustomToken()to sign in users.

You can create custom tokens with the Identity Platform Admin SDK,or use a third-party JWT library.

Before you begin

  • Install the Admin SDK.If you are using service account auto-discovery or an explicitly specified service account ID, make sure the service account you are using has at least the Service AccountToken Creator (roles/iam.serviceAccountTokenCreator) role.

  • Create and deploy a server endpoint that accepts sign-in credentials fromusers.

Creating custom tokens using the Admin SDK

The Admin SDK has a built-in method for creating custom tokens. At aminimum, you need to provide a uid. This can be any string that uniquelyidentifies the user or device. These tokens expire after one hour.

The following example shows how to create a custom token:

Node.js

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

Java

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

Python

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

Go

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)

C#

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

After you create a custom token, your app can use it tosign in a user.

Optionally, you can include additional claims on the custom token. These arepropagated to the user's ID token as top-level claims.

The following example shows how to add a premiumAccount claim:

Node.js

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); });

Java

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

Python

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

Go

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)

C#

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

Identity Platform complies with theOpenID Connect JWT specification.This means the following claims are reserved and cannot be specified:

  • acr
  • amr
  • at_hash
  • aud
  • auth_time
  • azp
  • cnf
  • c_hash
  • exp
  • firebase
  • iat
  • iss
  • jti
  • nbf
  • nonce
  • sub

Creating custom tokens using a third-party JWT library

If your backend is written in a language that the Admin SDK doesn't support,you can still manually create custom tokens. First,find a third-party JWT library for your language. Then, use that library to mint a JWT which includes thefollowing claims:

alg Algorithm "RS256"
iss Issuer Your project's service account email address.
sub Subject Your project's service account email address.
aud Audience "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit"
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 that this only controls the time when the custom token itself expires. Once you sign in a user with signInWithCustomToken(), they will remain signed in until they sign out or their session is invalidated.
uid The unique identifier of the signed-in user. Must be a string between 1-36 characters long.
claims (optional) Additional custom claims to include.

The following examples demonstrate how to create custom tokens in languagesthe Admin SDK does not support:

PHP

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 = "abc-123@a-b-c-123.iam.gserviceaccount.com";$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" => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit", "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");}

Ruby

Using ruby-jwt:

require "jwt"# Get your service account's email address and private key from the JSON key file$service_account_email = "service-account@my-project-abc123.iam.gserviceaccount.com"$private_key = OpenSSL::PKey::RSA.new "-----BEGIN PRIVATE KEY-----\n..."def create_custom_token(uid, is_premium_account) now_seconds = Time.now.to_i payload = {:iss => $service_account_email, :sub => $service_account_email, :aud => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit", :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 a custom token, your app can use it tosign in a user.

What's next

Creating custom tokens  |  Identity Platform Documentation  |  Google Cloud (2024)

FAQs

What can I do with a custom token? ›

Custom tokens give you complete control over the authentication process. You generate these tokens on your server, pass them back to a client device, and then call signInWithCustomToken() to sign in users. You can create custom tokens with the Identity Platform Admin SDK, or use a third-party JWT library.

How do I create an identity token? ›

Get an ID token
  1. Get an ID token from the metadata server.
  2. Use a connecting service to generate an ID token.
  3. Generate an ID token by impersonating a service account.
  4. Generate a generic ID token for development with Cloud Run and Cloud Functions.
  5. Generate an ID token using an external identity provider.

How do you generate tokens in Firebase? ›

The access tokens can be generated using a service account with proper permissions to your Realtime Database. Clicking the Generate New Private Key button at the bottom of the Service Accounts section of the Firebase console allows you to easily generate a new service account key file if you do not have one already.

How do I verify my custom token in Firebase? ›

To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.

How do token creators make money? ›

Ethereum developers commonly do this by bootstrapping new cryptocurrency projects and selling the created tokens on an exchange. Placing coins on a crypto exchange is called an Initial Coin Offering. This works just like a stock IPO and can generate significant funds if enough buyers are interested in the project.

Is it legal to create a crypto token? ›

Creating a cryptocurrency is generally legal, although some countries and jurisdictions have partially or fully banned cryptocurrency. In China, for example, raising money through virtual currencies has been illegal since 2017, and all cryptocurrency transactions have since been banned.

How to create a token using API? ›

To generate an API token

In Admin Center, click Apps and integrations in the sidebar, then select APIs > Zendesk APIs. Click the Settings tab, and make sure Token Access is enabled. Click the Add API token button to the right of Active API Tokens. The token is generated and displayed.

How do I manually create an access token? ›

In the upper-right corner of any page, click your profile photo, then click Settings. In the left sidebar, click Developer settings. In the left sidebar, under Personal access tokens, click Tokens (classic). Select Generate new token, then click Generate new token (classic).

How to create a token for free? ›

Table of Contents
  1. Introduction to how to create your own token. ...
  2. What to consider before creating your own token. ...
  3. Step 1: Connect Wallet via Web3.
  4. Step 2: Select network on which to create token.
  5. Step 3: Specify your Token's Features.
  6. Step 4: Create Token.
  7. Step 5: Agree to the terms and conditions.
  8. Step 6: Confirm Transaction.

What is a custom token? ›

Custom tokens are signed JWTs where the private key used for signing belongs to a Google service account.

How do I generate a token in Azure Devops? ›

Sign in to your organization ( https://dev.azure.com/{yourorganization} ).
  1. From your home page, open user settings and select Personal access tokens.
  2. Select + New Token.
  3. Name your token, select the organization where you want to use the token, and then set your token to automatically expire after a set number of days.
Mar 26, 2023

How do I generate Azure tokens? ›

There are two steps to acquire an Azure AD access token using the authorization code flow.
  1. Request an authorization code, which launches a browser window and asks for Azure user login. The authorization code is returned after the user successfully logs in.
  2. Use the authorization code to acquire the Azure AD access token.
Sep 28, 2022

How long does a Firebase token last? ›

Firebase ID tokens are short lived and last for an hour; the refresh token can be used to retrieve new ID tokens.

How do I know if my token is valid? ›

What to Check When Validating an Access Token
  1. Retrieve and parse your Okta JSON Web Keys (JWK), which should be checked periodically and cached by your application.
  2. Decode the access token, which is in JSON Web Token format.
  3. Verify the signature used to sign the access token.

How does Firebase use a custom auth system? ›

You can integrate Firebase Authentication with a custom authentication system by modifying your authentication server to produce custom signed tokens when a user successfully signs in. Your app receives this token and uses it to authenticate with Firebase.

What is the most profitable token? ›

Bitcoin – Coin With the Potential to Become one of the Most Profitable Crypto. Bitcoin was the first digital asset to come into existence in the crypto space. In fact, for its early investors, BTC has been the most profitable cryptocurrency to invest in.

How do crypto billionaires make money? ›

Crypto billionaires are a motley bunch—some have made their billions by providing products and services to the emerging ecosystem, while others have generated profits by taking advantage of crypto volatility.

Do you own tokens you create? ›

The player who creates a token is its owner. The token enters the battlefield under that player's control. 111.3. The spell or ability that creates a token may define the values of any number of characteristics for the token.

Do you need a license to create a cryptocurrency? ›

The license to undertake a cryptocurrency business within the jurisdiction of USA requires obtaining a Money Services Business from the Financial Crimes Enforcement Network (FinCEN) along with a Money Transmitter License from the respective state agencies within which the cryptocurrency business is undertaking its ...

How much does it cost to create a token? ›

On average if you are looking to start a decent ICO project, it will cost you between $500-$2000 for creating millions of ERC20 tokens.

Can I create my own NFT token? ›

Non-fungible tokens can be created directly on NFT platforms, allowing you to mint (the process of creating or producing something) and upload your artwork on a blockchain.

How do I create an online token? ›

  1. Install MetaMask. You need to have MetaMask installed with an amount of ETH to pay for contract deployment.
  2. Enter Details. Enter your preferred Token name and symbol. Choose your supply and Token type.
  3. Deploy Token. Confirm your transaction using MetaMask. Once deployed your Token is ready to use.

Can you create an app on a token? ›

An Application Token is an alphanumeric string that authorizes you to create an application. App tokens can be used as part of the authentication process to perform read operations through the API.

How do I create and deploy a token? ›

Creating a Deploy token

Sign in to your GitLab account. Go to the project (or group) you want to create deploy tokens for. Go to Settings > Repository. Expand the Deploy tokens section.

How do I create a JWT token online? ›

Generate a token in the https://jwt.io/ website by using the following steps:
  1. Select the algorithm RS256 from the Algorithm drop-down menu.
  2. Enter the header and the payload. ...
  3. Download the private key from the /home/vol/privatekey. ...
  4. Enter the downloaded private key in the Private Key field of the Verify Signature section.

What format is an access token? ›

A common format used for access tokens is JWT, and a standard structure is available.

How to generate token using username and password? ›

Get an access token based on username / password
  1. Have a user use their browser to request an authorization token (they would be asked to enter their username/password).
  2. Copy the authorization token from the browser and use it in the request header in a client (e.g. postman) to access my api.
Mar 26, 2020

What is the best platform to create a token? ›

Currently, there are multiple blockchain platforms available in the crypto ecosystem for creating crypto tokens. Among the list, the best blockchain platforms are Ethereum, Tron, and the BNB chain. All these popular blockchains are used to create a crypto token.

How much does it cost to create an ERC20 token? ›

Considering the above stages, the total cost of creating an ERC20 token can range from $10,000 to $55,000, depending on the complexity of the project. At Taksh IT Solutions, we have a team of experienced blockchain developers who can help you create a customized ERC20 token that meets your business requirements.

How do I create a custom ERC20 token? ›

Create an ERC20 Token on Kaleido
  1. Step 1: Create a Kaleido account. If you haven't already, sign up for a Kaleido account here. ...
  2. Step 2: Create a blockchain network. To get started, create a blockchain network. ...
  3. Step 3: Create a Token pool. ...
  4. Step 4: ERC20 Transactions. ...
  5. Step 5: Transferring Tokens.
Jan 27, 2023

What is an example of a design token? ›

A token can be a color, font style, unit of white space, or even a motion animation designed for a specific need. For example, instead of choosing one of many shades of green for an icon, we can apply a design token that is consistent with all similar usages across our products: color.

What are token examples? ›

In general, a token is an object that represents something else, such as another object (either physical or virtual), or an abstract concept as, for example, a gift is sometimes referred to as a token of the giver's esteem for the recipient.

How to generate token in API testing? ›

Use Access Tokens for Testing
  1. Go to the Management API v2 explorer page, and click the Set API Token button.
  2. Set the API Token field, and click Set Token.
  3. Under the Set API Token button, some new information is now displayed: the domain and token set, and the scopes that have been granted to this application.

How do I generate a token in Salesforce? ›

Generate an Initial Access Token
  1. From Setup, enter Apps in the Quick Find box, then select App Manager.
  2. Locate the OAuth connected app in the apps list, click. ...
  3. In the Initial Access Token for Dynamic Client Registration section, click Generate if an initial access token hasn't been created for the connected app.

How do I create an API bearer token? ›

The API bearer token's properties include an access_token / refresh_token pair and expiration dates. Tokens can be generated in one of two ways: If Active Directory LDAP or a local administrator account is enabled, then send a 'POST /login HTTP/1.1' API request to retrieve the bearer token.

What are tokens in Azure? ›

An access token contains claims that you can use in Azure Active Directory B2C (Azure AD B2C) to identify the granted permissions to your APIs. To call a resource server, the HTTP request must include an access token. An access token is denoted as access_token in the responses from Azure AD B2C.

How do I create an access token and refresh token? ›

Authorization
  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.

How do I get a Microsoft token? ›

To get an access token, your app must be registered with the Microsoft identity platform and be granted Microsoft Graph permissions by a user or administrator. This article provides an overview of the Microsoft identity platform, access tokens, and how your app can get access tokens.

What is the difference between token and access token? ›

Unlike access tokens, which are opaque objects that cannot be inspected by the application, ID tokens are meant to be inspected and used by the application. Information from the token, such as Who signed the token or the identity for whom the ID token was issued, is available for use by the application.

What is the lifetime of Azure access token? ›

Access and ID token lifetimes (minutes) - The lifetime of the OAuth 2.0 bearer token and ID tokens. The default is 60 minutes (1 hour). The minimum (inclusive) is 5 minutes. The maximum (inclusive) is 1,440 minutes (24 hours).

What is the life span of Azure token? ›

The expiry time of token is approx. 30 mins to 1 hr.

How do you convert tokens to real money? ›

Cryptocurrency can be converted through an exchange or a broker. One can use a peer-to-peer platform to convert digital coins into cash, by just selling it. Also this system entails lesser fees and guarantees a better exchange rate than one gets through a third-party brokerage.

What can you do with an NFT token? ›

NFTs can be traded and exchanged for money, cryptocurrencies, or other NFTs—it all depends on the value the market and owners have placed on them. For instance, you could use an exchange to create a token for an image of a banana. Some people might pay millions for the NFT, while others might think it worthless.

How do you convert tokens to money? ›

There are two most common ways to convert crypto to cash. One of them is getting the procedure completed through an exchange or a broker. Deposit your cryptocurrency into an exchange and request a withdrawal in the currency of your choice. The funds will be paid to your bank account.

Can token be used as money? ›

The token is also used as a medium of exchange, as a store of value, and as a unit of account. Digital currencies using decentralized blockchain technology are also a form of token money.

Top Articles
Gender Affirmation Surgery: What Happens, Benefits & Recovery
Lost Wallet? Take These 5 Steps Now - NerdWallet Canada
Craigslist Livingston Montana
Urist Mcenforcer
Body Rubs Austin Texas
Phenix Food Locker Weekly Ad
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
Tripadvisor Near Me
Syracuse Jr High Home Page
Cooking Fever Wiki
Meritas Health Patient Portal
Colts Snap Counts
iLuv Aud Click: Tragbarer Wi-Fi-Lautsprecher für Amazons Alexa - Portable Echo Alternative
Unlv Mid Semester Classes
History of Osceola County
Ibukunore
Craigslist Maui Garage Sale
Www.publicsurplus.com Motor Pool
Craigslist Prescott Az Free Stuff
Pecos Valley Sunland Park Menu
Which Sentence is Punctuated Correctly?
Jurassic World Exhibition Discount Code
Annapolis Md Craigslist
Primerica Shareholder Account
Prévisions météo Paris à 15 jours - 1er site météo pour l'île-de-France
JD Power's top airlines in 2024, ranked - The Points Guy
How does paysafecard work? The only guide you need
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Maybe Meant To Be Chapter 43
Craigslist West Seneca
Skip The Games Ventura
Bella Thorne Bikini Uncensored
Search All of Craigslist: A Comprehensive Guide - First Republic Craigslist
Daly City Building Division
A Comprehensive 360 Training Review (2021) — How Good Is It?
Dispensaries Open On Christmas 2022
3 Zodiac Signs Whose Wishes Come True After The Pisces Moon On September 16
Lyndie Irons And Pat Tenore
Royals Yankees Score
Wordle Feb 27 Mashable
War Room Pandemic Rumble
Keci News
Zom 100 Mbti
Craigslist Pets Charleston Wv
Bradshaw And Range Obituaries
Craiglist.nj
Uno Grade Scale
Game Like Tales Of Androgyny
2000 Fortnite Symbols
Inloggen bij AH Sam - E-Overheid
Koniec veľkorysých plánov. Prestížna LEAF Academy mení adresu, masívny kampus nepostaví
The Love Life Of Kelsey Asbille: A Comprehensive Guide To Her Relationships
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6009

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.