Skip to content

Commit ba6ef7b

Browse files
authored
feat(docs): add new custom jwt docs (#643)
* feat(docs): add new custom jwt docs add new custom jwt docs * feat(docs): add test panel image add test panel image * chore: add emoji add emoji * fix(docs): fix the build error fix the build error
1 parent 75696a8 commit ba6ef7b

File tree

4 files changed

+169
-0
lines changed

4 files changed

+169
-0
lines changed
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
---
2+
sidebar_position: 10
3+
---
4+
5+
import Availability from '@components/Availability';
6+
7+
import CustomJwtLanding from './assets/custom-jwt-landing.webp';
8+
import CustomJwtDetails from './assets/custom-jwt-details.webp';
9+
import TestResult from './assets/test-result.webp';
10+
11+
# 🎫 Custom JWT claims
12+
13+
<Availability cloud oss="comingSoon" />
14+
15+
## Introduction
16+
17+
JSON web token (JWT) is a popular way to represent claims securely between two parties. Logto issues JWT format access tokens and ID tokens for your applications for authentication and access control. These JWT tokens carry important user information and permissions and pass them between Logto server and your client applications securely.
18+
19+
Usually, the information contained in JWT is determined by the authentication server. According to the OAuth 2.0 protocol, several standard claims are commonly used in JWT tokens, such as `sub`, `iss`, `aud`, `exp`, `iat`, and `jti`. (See [RFC7519](https://datatracker.ietf.org/doc/html/rfc7519) for more details).
20+
21+
However, there are countless scenarios where JWT is used for further verification or data transmission needs, and common JWT claims may often not meet the needs. We understand that you may have specific requirements for the JWT claims in your applications. Therefore, Logto allows you to customize the JWT claims in the access tokens issued by Logto. You can add custom claims to the JWT tokens to meet your specific needs.
22+
23+
## How does it work?
24+
25+
Logto allows you to insert custom claims into the `access token` through a callback function `getCustomJwtClaims`. You may provide your implementation of the `getCustomJwtClaims` function to return an object of custom claims. The return value will be merged with Logto built-in claims and included in the JWT `access token`.
26+
27+
```mermaid
28+
sequenceDiagram
29+
participant U as User or user agent
30+
participant IdP as Logto (identity provider)
31+
participant SP as Service Provider
32+
33+
autonumber
34+
U ->> IdP: Auth request (with credentials)
35+
activate IdP
36+
IdP-->>IdP: Validate credentials &<br/>generate raw access token payload
37+
rect rgb(191, 223, 255)
38+
note over IdP: Custom JWT
39+
IdP->>IdP: Run custom JWT claims script (`getCustomJwtClaims`) &<br/>get extra JWT claims
40+
end
41+
IdP-->>IdP: Merge raw access token payload and extra JWT claims
42+
IdP-->>IdP: Sign & encrypt payload to get JWT access token
43+
deactivate IdP
44+
IdP-->>U: Issue JWT-format access token
45+
par Get service via API
46+
U->>SP: service request (with JWT access token)
47+
SP-->>U: service response
48+
end
49+
```
50+
51+
:::note
52+
Logto build-in JWT claims can NOT be overridden or modified. Custom claims will be added to the JWT token as additional claims. If any custom claims conflict with the built-in claims, those custom claims will be ignored.
53+
:::
54+
55+
## Create a custom JWT claims script
56+
57+
To add custom claims to the JWT access token, you need to provide a script that returns an object of custom claims. The script should be a `JavaScript` function that returns an object of custom claims.
58+
59+
Visit the **Logto Console** and click on the **Custom JWT** navigation item in the left sidebar.
60+
61+
![Custom JWT landing](./assets/custom-jwt-landing.webp)
62+
63+
There are two different types of access tokens that you can customize the JWT claims for:
64+
65+
- **User Access Token**: The access token issued for the end users. E.g. for Web applications or mobile applications.
66+
- **Machine-to-Machine Access Token**: The access token issued for the services or applications. E.g. for machine-to-machine applications.
67+
68+
Different types of access tokens may have different token payload contexts. You may customize the JWT claims for each type of access token separately.
69+
70+
Pick any type of access token you want to customize the JWT claims for, and click on the **Add custom claims** button to create a new script.
71+
72+
## Implement the `getCustomJwtClaims` function
73+
74+
In the `Custom JWT` details page, you may find the script editor to write your custom JWT claims script. The script should be a `JavaScript` function that returns an object of custom claims.
75+
76+
![Custom JWT details](./assets/custom-jwt-details.webp)
77+
78+
### Edit the script
79+
80+
Use the code editor on the left side to modify the script. A default `getCustomJwtClaims` with an empty object return value is provided for you to start with. You may modify the function to return an object of your own custom claims.
81+
82+
This editor uses the javascript language server to provide basic syntax highlighting, code completion, and error checking. A comprehensive JsDoc is also provided to help you understand the function signature and the return value.
83+
84+
:::info
85+
This function will be exported as a module. Make sure remain the function name as `getCustomJwtClaims` so the module can export the function correctly.
86+
:::
87+
88+
```javascript
89+
const getCustomJwtClaims = async ({ token, context, environmentVariables }) => {
90+
return {};
91+
};
92+
```
93+
94+
### Input parameters
95+
96+
The `getCustomJwtClaims` function takes an object as the input parameter. The object contains the standard token payload, additional user information (only available for user access token), and the environment variables you set for the script.
97+
98+
You may find the detailed type definition of the token payload object and user data object on the right side of the page. The IntelliSense of the editor will also help you access these properties of the input object correctly.
99+
100+
**User access token data object:**
101+
102+
| Property | Description | Type |
103+
| -------------------- | ------------------------------------------------ | ------------- |
104+
| `jti` | The unique JWT id | `string` |
105+
| `aud` | The audience of the token | `string` |
106+
| `scope` | The scopes of the token | `string` |
107+
| `clientId` | The client id of the token | `string` |
108+
| `accountId` | The user id of the token | `string` |
109+
| `expiresWithSession` | Whether the token will expire with the session | `boolean` |
110+
| `grantId` | The current authentication grant id of the token | `string` |
111+
| `gty` | The grant type of the token | `string` |
112+
| `kind` | The token kind | `AccessToken` |
113+
114+
**Machine-to-machine access token data object:**
115+
116+
| Property | Description | Type |
117+
| ---------- | -------------------------- | ------------------- |
118+
| `jti` | The unique JWT id | `string` |
119+
| `aud` | The audience of the token | `string` |
120+
| `scope` | The scopes of the token | `string` |
121+
| `clientId` | The client id of the token | `string` |
122+
| `kind` | The token kind | `ClientCredentials` |
123+
124+
**User data object:**
125+
126+
For user access token, Logto provides additional user data context for you to access. The user data object contains all the user profile data and organization membership data you may need to set up the custom claims. Please check [Users](../../references/users/README.md) and [Organizations](../../recipes/organizations/README.mdx) for more details.
127+
128+
**Environment variables:**
129+
130+
Use the **Set environment variables** section on the right to set up the environment variables for your script. You may use these variables to store sensitive information or configuration data that you don't want to hardcode in the script. e.g. API keys, secrets, or URLs.
131+
132+
All the environment variables you set here will be available in the script. Use the `environmentVariables` object in the input parameter to access these variables.
133+
134+
### Fetch external data
135+
136+
You may use the node built-in `fetch` function to fetch external data in your script. The `fetch` function is a promise-based function that allows you to make HTTP requests to external APIs.
137+
138+
```javascript
139+
const getCustomJwtClaims = async ({ environmentVariables }) => {
140+
const response = await fetch('https://api.example.com/data', {
141+
headers: {
142+
Authorization: `Bearer ${environmentVariables.API_KEY}`,
143+
},
144+
});
145+
146+
const data = await response.json();
147+
148+
return {
149+
data,
150+
};
151+
};
152+
```
153+
154+
:::note
155+
Be aware, any external data fetching may introduce latency to the token issuing process. Make sure the external API is reliable and fast enough to meet your requirements. Additionally:
156+
157+
- Handle the error and timeout properly in your script to avoid the token issuing process being blocked.
158+
- Use proper authorization headers to protect your external API from unauthorized access.
159+
:::
160+
161+
### Test the script
162+
163+
Make sure to test your script before saving it. Click on the `Test Context` tab on the right side of the page to modify the mock token payload and user data context for testing.
164+
165+
Click on the `Run test` on the right-top corner of the editor to run the script with the mock data. The output of the script will be displayed in the `Test Result` drawer.
166+
167+
![Test result](./assets/test-result.webp)
168+
169+
Click on the **Create** button to save the script. The custom JWT claims script will be saved and applied to the access token issuing process.
Binary file not shown.
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)