DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Set up OAuth JWT Flow and mTLS in the Salesforce Connector for a MuleSoft App
  • On-Demand-Schedulers With MuleSoft CloudHub APIs
  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • Exploring ML.NET Catalogs and Use Cases

Trending

  • A Guide to Container Runtimes
  • Solid Testing Strategies for Salesforce Releases
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Unlocking AI Coding Assistants Part 2: Generating Code
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Create JWT Using DataWeave JWT Library

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.

By 
Ujala Kumar Yadav user avatar
Ujala Kumar Yadav
·
Jul. 11, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.1K Views

Join the DZone community and get the full member experience.

Join For Free

Recently 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:

Plain Text
 
{
	"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:

Plain Text
 
{
	"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.

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.

Copy the dependency snippet from the Exchange


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.

Add the transform message to read the private key in the Mule application and store it in a variable

Plain Text
 
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

 
{

     "alg": "RS256",

     "typ": "JWT"

}


2

payload

Object

JWT Payload

 
{

     iss: "jwt-rsa-demo@test.com",

     aud: 'https://test.mulesoft.com',

     iat: (now()) as Number { unit: 'seconds' },

     exp: (now() + |PT7200S|) as Number { unit: 'seconds' } 

}


3

key

String

RSA private keys.
  JWT library supports PKCS#1 or PKCS#8 formatted private keys.

vars.privateKey

4

algorithm

String

The supported RSA algorithms are:

  • RS256: Sha256withRSA
  • RS384: Sha384withRSA
  • RS512: Sha512withRSA

Sha256withRSA

DataWeave:

Plain Text
 
%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.

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

 
{

       "alg": "HS256",

       "typ": "JWT"

}


2

payload

Object

JWT Payload

 
{

       iss: "jwt-hmac-demo@test.com",

       aud: 'https://test.mulesoft.com',

       iat: (now()) as Number { unit: 'seconds' },

       exp: (now() + |PT7200S|) as Number { unit: 'seconds' }

}


3

signingKey

String

Secret Key

"MuleJWTPassword@2023"

4

algorithm

String

The supported HMAC algorithms are:

  • HS256: HmacSHA256
  • HS384: HmacSHA384
  • HS512: HmacSHA512

HmacSHA256

DataWeave:

Plain Text
 
%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:
Plain Text
 
{
    "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:
Plain Text
 
{
    "token": "eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiand0LWhtYWMtZGVtb0B0ZXN0LmNvbSIsImF1ZCI6ICJodHRwczovL3Rlc3QubXVsZXNvZnQuY29tIiwiaWF0IjogMTY5NjQ5MzIzOSwiZXhwIjogMTY5NjQ5NjgzOX0.sAiK-Bto_8JS4WLJa3nFoSYCIIv3IiXYLyL0QKXB-hQ",
    "expiration": "2023-10-05T14:36:29.62+05:30"
}


Validation

  • Validate RSA JWT using public key:
  • Validate RSA JWT using public keyValidate HMAC JWT using a secret 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.

Library MuleSoft Algorithm JWT (JSON Web Token) Payload (computing)

Published at DZone with permission of Ujala Kumar Yadav. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Set up OAuth JWT Flow and mTLS in the Salesforce Connector for a MuleSoft App
  • On-Demand-Schedulers With MuleSoft CloudHub APIs
  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • Exploring ML.NET Catalogs and Use Cases

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!