Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • How to Use the OAuth 2.0 State Parameter
      • Reauthentication
      • How to Use Social/Enterprise Login Providers Without AuthUI
      • Passwordless Login for Apple App Store Review
      • Setup local development environment for Cookie-based authentication
      • Forgot/Reset Password settings
      • Phone number validation
      • Set Password Expiry
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Languages and Localization
    • Custom Email and SMS Templates
    • Directly accessing Authgear Endpoint
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Prerequisites
  • Enable Access Token for your App
  • Create a new Event Hook
  • Verify the Custom Field in a JWT token

Was this helpful?

Edit on GitHub
  1. How-To Guides
  2. Integrate

Add custom fields to a JWT Access Token

Learn how to add custom attributes to a JWT Access Token using Authgear

PreviousIntegrateNextUser Analytics by Google Tag Manager

Last updated 10 months ago

Was this helpful?

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 attributes to a JWT access token payload using Authgear and Javascript .

Here's an example of the and an explanation of their values.

You can also to on the Authegear Portal.

Prerequisites

  • An Authgear account: You need an Authgear account to follow this guide. If you don't have one, you can on the Authgear website.

  • A Registered App: You need a (client) in Authgear.

Enable Access Token for your App

Make sure the option Issue JWT as access token is enabled in your Application settings in the Portal.

  1. Log into your .

  2. Navigate to the Applications tab and choose the existing App.

  3. On the App Configuration dashboard, locate the "Access token" section.

  4. Make the toggle Issue JWT as access token switch on.

Create a new Event Hook

  1. Navigate to your Authgear Dashboard's Advanced->Hooks section.

  2. Add a new Blocking Event.

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

  1. Click on Edit Script under the Config option.

  2. Copy and paste the following into the editor:

import { EventOIDCJWTPreCreate, HookResponse } from "https://deno.land/x/authgear_deno_hook@v1.0.0/mod.ts";

export default async function(e: EventOIDCJWTPreCreate): Promise<HookResponse> {
  return {
    mutations:{
      jwt: {
        payload:{
          ...e.payload.jwt.payload,
          standard_attributes: e.payload.user.standard_attributes,
          custom_attributes: e.payload.user.custom_attributes
        }
      }
    },
    is_allowed: true
  };
}
  1. Click on Finish Editing.

  2. Back to the Hooks page from the navigation bar and click on the Save button at the top of the page.

Verify the Custom Field in a JWT token

There are two ways to test it:

  • If you created the application type OIDC Client Application, you need to follow the steps below. Expand it to see instructions.

Verify the custom field in the JWT Token with OIDC Client Application

This part explains how to retrieve an access token using OpenID App Endpoints and check if newly added custom attributes are in place in the JWT Access token.

Prerequisites

  • Make sure that you have a registered app type of OIDC Client Application in Authgear Portal.

Step 1: Obtain the necessary parameters

Open your OpenID Auth App configuration, and find Client ID, Client Secret, and check Authorization, and Token endpoints. You will use them in the next steps.

Step 2: Construct the authorization endpoint URL

The URL for this endpoint is usually provided by the authorization server and includes parameters specifying the requested scope, client_id, and response_type. Here's an example URL for the authorization endpoint:

https://<YOUR_AUTHGEAR_ENDPOINT>/oauth2/authorize?client_id={YOUR_CLIENT_ID}&response_type=code&scope=openid

Replace <YOUR_AUTHGEAR_ENDPOINT> with your Authgear server's domain, YOUR_CLIENT_ID with your application's Client ID from OpenID App.

Step 3: Redirect the user to the authorization endpoint

Next, you need to redirect the user to the authorization endpoint. You can just put the URL in your browser and log in with a user credential you are interested to retrieve an access token for. After successful authentication and consent, the Authgear will redirect the user back to your specified redirect URI, including an authorization code as a query parameter. You will need the code in the next step

Step 4: Obtain an access token

You need to make a request to the OpenID App's Token endpoint to exchange the authorization code we retrieved in the previous step for an access token.

  • The token endpoint URL is usually something like https://<YOUR_AUTHGEAR_ENDPOINT>/oauth2/token.

  • Include parameters such as grant_type=authorization_code, code=AUTHORIZATION_CODE, client_id=YOUR_CLIENT_ID, client_secret=YOUR_CLIENT_SECRET, and redirect_uri=YOUR_REDIRECT_URI.

  • Make a POST request to the token endpoint to obtain the access token.

curl --request POST \
  --url 'https://<YOUR_AUTHGEAR_ENDPOINT>/oauth2/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type=authorization_code \
  --data code={YOUR_AUTHORIZATION_CODE} \
  --data redirect_uri={YOUR_REDIRECT_URI} \
  --data 'client_id={YOUR_CLIENT_ID}' \
  --data client_secret={YOUR_CLIENT_SECRET} \
  --data scope=openid

Step 5: Verify custom attributes in the access token

\

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

In the above code, we are importing the necessary modules such as HookResponse and EventOIDCJWTPreCreate which are types from the Authgear hook . We modify the JWT payload by adding (e.payload.user.standard_attributes) and (e.payload.user.custom_attributes) of the user.

You can do this by on your application server side using a JWT decoder and inspecting the payload.

Finally, we can debug the access token using the to see if the custom field and value we added previously are there inside the JWT payload.

Events
Deno
Typescript library
Standard Attributes
Custom Attributes
decoding the JWT token
JWT Debugger tool
User Profiles
Hooks
fields in the JWT Access Tokens by default
add custom attributes
User Profiles
create it for free
registered application
Authgear account