Add custom fields to a JWT Access Token
Learn how to add custom attributes to a JWT Access Token using Authgear
Last updated
Learn how to add custom attributes to a JWT Access Token using Authgear
Last updated
JWTs (JSON Web Tokens) are a common method for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. With Authgear, it is straightforward to add custom fields to your JWT access tokens.
This how-to guide will walk you through the process of adding custom fields such as User Profiles attributes to a JWT access token payload using Authgear and Javascript Hooks.
Here's an example of the fields in the JWT Access Tokens by default and an explanation of their values.
You can also add custom attributes to User Profiles on the Authegear Portal.
An Authgear account: You need an Authgear account to follow this guide. If you don't have one, you can create it for free on the Authgear website.
A Registered App: You need a registered application (client) in Authgear.
Make sure the option Issue JWT as access token is enabled in your Application settings in the Portal.
Log into your Authgear account.
Navigate to the Applications tab and choose the existing App.
On the App Configuration dashboard, locate the "Access token" section.
Make the toggle Issue JWT as access token switch on.
With the use of Hooks, Authgear provides flexibility for adding custom logic to your authentication pipeline. You can create a Hook which is triggered any of these Events about to occur. For example, oidc.jwt.pre_create
the event happens just before issuing the JWT access token and it can be used to put extra information into the token.
Navigate to your Authgear Dashboard's Advanced->Hooks section.
Add a new Blocking Event.
Choose the Block Hook Type as the TypeScript and set the Event option to JWT access token pre-create. You will write a new Typescript function from scratch.
Click on Edit Script under the Config option.
Copy and paste the following into the editor:
Click on Finish Editing.
Back to the Hooks page from the navigation bar and click on the Save button at the top of the page.
In the above code, we are importing the necessary modules such as HookResponse
and EventOIDCJWTPreCreate
which are types from the Authgear Deno hook Typescript library. We modify the JWT payload by adding Standard Attributes(e.payload.user.standard_attributes
) and Custom Attributes(e.payload.user.custom_attributes
) of the user.
There are two ways to test it:
You can do this by decoding the JWT token on your application server side using a JWT decoder and inspecting the payload.
If you created the application type OIDC Client Application, you need to follow the steps below. Expand it to see instructions.