Create JWT Using DataWeave JWT Library
This article describes the process of creating JWT using the DataWeave JWT Library available in Mulesoft Exchange, which supports both HMAC and RSA algorithms.
Join the DZone community and get the full member experience.
Join For FreeRecently in one of my projects, there was a requirement to create JWT within the MuleSoft application and send that as an OAuth token to the backend for authentication. After doing some research, I got to know several ways to create JWT like Java code, DataWeave code, JWT sign module, etc. Java code can be complex to implement, Dataweave code does not work for the RSA algorithm and the client didn’t want to use a custom module like the JWT sign module. Finally, I got to know about the DataWeave JWT Library available in MuleSoft Exchange.
In this blog, I will be describing the process of creating JWT using the Dataweave JWT Library available in Mulesoft Exchange which supports both HMAC and RSA algorithms.
Background
JSON Web Token
JSON Web Token (JWT) is an open standard that provides a mechanism for securely transmitting data between parties as a JSON object. JWTs are relatively smaller in size and because of that they can be sent through a URL, POST parameter, or HTTP header, and it is transmitted quickly.
JSON Web Token Structure
JSON Web Tokens are made of three parts separated by dots (.), which are:
1. Header
The first part is the Base64-URL encoded header which typically consists of two fields: the type of the token, which is JWT, and the signing algorithm being used (HMAC or RSA).
For example:
{
"alg": "RS256",
"typ": "JWT"
}
2. Payload
The second part of the token is the payload, which are Base64-URL encoded claims. Claims are details about the user and some additional data.
For example:
{
"sub": "jwt-demo@test.com",
"aud": "https://test.mulesoft.com",
"exp": "1661508617"
}
Please note that for signed tokens, this information is protected against tampering, but it is readable by anyone. Do not put sensitive information in the payload or header parts of a JWT unless it is encrypted.
3. Signature
To create the signature part we need to take the Base64-URL encoded header, the Base64-URL encoded payload, a private key or secret key based on the algorithm type (HMAC or RSA), and the algorithm specified in the header, and sign that.
- In the case of an HMAC signature, a secret key is used to sign the JWT by the client, and the same secret key is used to validate the JWT by the server.
- In the case of an RSA signature, the private key is used to sign the JWT by the client, and the public key is used to validate the JWT by the server. This ensures that the message is not changed along the way and that the sender of the JWT is who it says it is.
Below is an example of JWT for the above-encoded header and payload, which is signed with a private key:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqd3QtZGVtb0B0ZXN0LmNvbSIsImF1ZCI6Imh0dHBzOi8vdGVzdC5tdWxlc29mdC5jb20iLCJleHAiOjE2NjE1MDg2MTd9.WnXOmrIv2SRF940x5qGuiRUkPJ14rBMnDRc53NLCf8LbJXEiwiSlKaulQGwRwBsBBG1C2DcANVqabC1KkeCen5D1dKaaabGo8BtV83qiP9FyKIhRgl81ldzOZ0QuybqBF78-Tq8LpjAX6W4HIlU5Im6MhgARnWKillxPbnwK8t_AVxIFxl2JW_h0gNbqT9tnOR2YDFm3gNlfLvHEu01FgI8LW9VQLvEuCsEMSCaz7-t1JsQ9nH8wGoVnmU0NgCyRBMd3F0hoCDzIP1PMJSceOHVdlK4hsmsjmDLsVUT0aInhoWqeyVcJkoULmBB34VUazV0yjXLzup26jUvfFxkwlA
Walkthrough
Step 1
Go to Dataweave JWT Library in MuleSoft Exchange.
Step 2
Copy the dependency snippet from the Exchange and add it to your project’s pom.xml dependencies section.
This will import the Dataweave JWT Library from MuleSoft Exchange to your MuleSoft application.
Step 3
Add a transform message in your flow to create JWT.
Create JWT With RSA Algorithm
- Step 1: Add the transform message to read the private key in the Mule application and store it in a variable.
output application/json
---
readUrl("classpath://pkcs1-rsa256-privatekey.pem","text/plain") replace "\r" with ""
Here, the private key is present under the src/main/resources folder and we are reading the private key into Mule flow using the DataWeave readUrl
function. You can also load the private key using the file read connector or any other way like loading from Azure Key Vault, AWS Secret Manager, etc. as per use case requirement. Also, you need to check the new line character in your private key. If it is “\r\n
” instead of “\n
” then we need to remove the extra “\r
” like above. The JWT library supports private keys with the new line character “\n
”.
- Step 2: Add the transform message to create the JWT.
Here, we need to pass the 4 parameters below to the JWT function.
Sr. No | Parameter | Datatype | Description | Example |
---|---|---|---|---|
1 |
header |
Object |
JWT Header |
|
2 |
payload |
Object |
JWT Payload |
|
3 |
key |
String |
RSA private keys. |
|
4 |
algorithm |
String |
The supported RSA algorithms are:
|
Sha256withRSA |
DataWeave:
%dw 2.0
import * from jwt::RSA
output application/json
---
{
token: JWT(
{
"alg": "RS256",
"typ": "JWT"
},
{
iss: "jwt-rsa-demo@test.com",
aud: 'https://test.mulesoft.com',
iat: (now()) as Number { unit: 'seconds' },
exp: (now() + |PT7200S|) as Number { unit: 'seconds' }
},
vars.privateKey as String,
'Sha256withRSA'
),
expiration: (now() + |PT7150S|)
}
Create JWT With HMAC Algorithm
- Step 1: Add the transform message to create the JWT.
Here, we need to pass the 4 parameters below to the JWT function.
Sr. No. | Parameter | Datatype | Description | Example |
---|---|---|---|---|
1 |
header |
Object |
JWT Header |
|
2 |
payload |
Object |
JWT Payload |
|
3 |
signingKey |
String |
Secret Key |
|
4 |
algorithm |
String |
The supported HMAC algorithms are:
|
|
DataWeave:
%dw 2.0
import * from jwt::HMAC
output application/json
var secretKey = "MuleJWTPassword@2023"
---
{
token: JWT(
{
"alg": "HS256",
"typ": "JWT"
},
{
iss: "jwt-hmac-demo@test.com",
aud: 'https://test.mulesoft.com',
iat: (now()) as Number { unit: 'seconds' },
exp: (now() + |PT7200S|) as Number { unit: 'seconds' }
},
secretKey as String,
'HmacSHA256'
),
expiration: (now() + |PT7150S|)
}
Step 4
Trigger the request and it will generate JWT.
- JWT with RSA output:
{
"token": "eyJhbGciOiAiUlMyNTYiLCJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiand0LXJzYS1kZW1vQHRlc3QuY29tIiwiYXVkIjogImh0dHBzOi8vdGVzdC5tdWxlc29mdC5jb20iLCJpYXQiOiAxNjk2NDkzODQwLCJleHAiOiAxNjk2NDk3NDQwfQ.q50ao_-1_ke7ZIizZYgz_914q8JcISWk8uCC0h08FtzlUJYWU0ss7M0gtBJSnDa3e1hAsJ2MlmKhVjL7wXbkYNRVtdCk6N1RC6dEJ2xLOPKMObvcSHvt9e5sTWOPqCBW4sZOQm9xMkCqWqkHAJ5wZzvDGOlo7K0I-23b2AhqESDqVGXNXdWKvgwVGtH1okL7PKy9aQw7grJ9iB6iV_yaFgGX82gu0m1QilF83VHvAy7sWq7RYk54FmI09U45-CXYtX_tpaq3Y1vjaGjHmkKqPfJnqO4ysBiRICvxhRcRqQgONqUSu7YpV59JoUG66r2ONnS9NFJXQSBVq7-GQl0g4A",
"expiration": "2023-10-05T14:46:30.505+05:30"
}
- JWT with HMAC output:
{
"token": "eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiand0LWhtYWMtZGVtb0B0ZXN0LmNvbSIsImF1ZCI6ICJodHRwczovL3Rlc3QubXVsZXNvZnQuY29tIiwiaWF0IjogMTY5NjQ5MzIzOSwiZXhwIjogMTY5NjQ5NjgzOX0.sAiK-Bto_8JS4WLJa3nFoSYCIIv3IiXYLyL0QKXB-hQ",
"expiration": "2023-10-05T14:36:29.62+05:30"
}
Validation
- Validate RSA JWT using public key:
- Validate HMAC JWT using a secret key:
Limitations
DataWeave JWT Library does not support encrypted private keys to generate JWT using the RSA algorithm. If the requirement is to create JWT using the RSA algorithm with an encrypted private key, you can use either custom Java code or JWT Sign Module.
Published at DZone with permission of Ujala Kumar Yadav. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments