Create JWT Utilizing DataWeave JWT Library – DZone – Uplaza

Not too long ago in one in all my tasks, there was a requirement to create JWT throughout the MuleSoft software and ship that as an OAuth token to the backend for authentication. After performing some analysis, I obtained to know a number of methods to create JWT like Java code, DataWeave code, JWT signal module, and so on. Java code will be advanced to implement, Dataweave code doesn’t work for the RSA algorithm and the shopper didn’t need to use a customized module just like the JWT signal module. Lastly, I obtained to know in regards to the DataWeave JWT Library out there in MuleSoft Change.

On this weblog, I will probably be describing the method of making JWT utilizing the Dataweave JWT Library out there in Mulesoft Change which helps each HMAC and RSA algorithms.

Background

JSON Net Token

JSON Net Token (JWT) is an open normal that gives a mechanism for securely transmitting knowledge between events as a JSON object. JWTs are comparatively smaller in dimension and due to that they are often despatched via a URL, POST parameter, or HTTP header, and it’s transmitted rapidly.

JSON Net Token Construction

JSON Net Tokens are manufactured from three elements separated by dots (.), that are:

1. Header

The primary half is the Base64-URL encoded header which usually consists of two fields: the kind of the token, which is JWT, and the signing algorithm getting used (HMAC or RSA).

For instance:

{
	"alg": "RS256",
    "typ": "JWT"
}

2. Payload

The second a part of the token is the payload, that are Base64-URL encoded claims. Claims are particulars in regards to the person and a few further knowledge.

For instance:

{
	"sub": "jwt-demo@test.com",
    "aud": "https://test.mulesoft.com",
    "exp": "1661508617"
}

Please notice that for signed tokens, this data is protected towards tampering, however it’s readable by anybody. Don’t put delicate data within the payload or header elements of a JWT except it’s encrypted.

3. Signature

To create the signature half we have to take the Base64-URL encoded header, the Base64-URL encoded payload, a personal key or secret key based mostly on the algorithm kind (HMAC or RSA), and the algorithm specified within the header, and signal that.

  • Within the case of an HMAC signature, a secret secret is used to signal the JWT by the shopper, and the identical secret secret is used to validate the JWT by the server.
  • Within the case of an RSA signature, the personal secret is used to signal the JWT by the shopper, and the general public secret is used to validate the JWT by the server. This ensures that the message will not be modified alongside the best way and that the sender of the JWT is who it says it’s.

Under is an instance of JWT for the above-encoded header and payload, which is signed with a personal key:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqd3QtZGVtb0B0ZXN0LmNvbSIsImF1ZCI6Imh0dHBzOi8vdGVzdC5tdWxlc29mdC5jb20iLCJleHAiOjE2NjE1MDg2MTd9.WnXOmrIv2SRF940x5qGuiRUkPJ14rBMnDRc53NLCf8LbJXEiwiSlKaulQGwRwBsBBG1C2DcANVqabC1KkeCen5D1dKaaabGo8BtV83qiP9FyKIhRgl81ldzOZ0QuybqBF78-Tq8LpjAX6W4HIlU5Im6MhgARnWKillxPbnwK8t_AVxIFxl2JW_h0gNbqT9tnOR2YDFm3gNlfLvHEu01FgI8LW9VQLvEuCsEMSCaz7-t1JsQ9nH8wGoVnmU0NgCyRBMd3F0hoCDzIP1PMJSceOHVdlK4hsmsjmDLsVUT0aInhoWqeyVcJkoULmBB34VUazV0yjXLzup26jUvfFxkwlA

Walkthrough

Step 1

Go to Dataweave JWT Library in MuleSoft Change.

Step 2

Copy the dependency snippet from the Change and add it to your venture’s pom.xml dependencies part.

It will import the Dataweave JWT Library from MuleSoft Change to your MuleSoft software.

Step 3

Add a rework message in your circulation to create JWT.

Create JWT With RSA Algorithm

  • Step 1: Add the rework message to learn the personal key within the Mule software and retailer it in a variable.

output software/json
---
readUrl("classpath://pkcs1-rsa256-privatekey.pem","text/plain") change "r" with ""

Right here, the personal secret is current below the src/major/assets folder and we’re studying the personal key into Mule circulation utilizing the DataWeave readUrl operate. You can even load the personal key utilizing the file learn connector or some other approach like loading from Azure Key Vault, AWS Secret Supervisor, and so on. as per use case requirement. Additionally, you have to verify the brand new line character in your personal key. Whether it is “rn” as an alternative of “n” then we have to take away the additional “r” like above. The JWT library helps personal keys with the brand new line character “n”.

  • Step 2: Add the rework message to create the JWT.

Right here, we have to cross the 4 parameters beneath to the JWT operate.

Sr. No Parameter Datatype Description Instance

1

header

Object

JWT Header

{

     "alg": "RS256",

     "typ": "JWT"

}

2

payload

Object

JWT Payload

{

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

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

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

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

}

3

key

String

RSA personal keys.
  JWT library helps PKCS#1 or PKCS#8 formatted personal keys.

vars.privateKey

4

algorithm

String

The supported RSA algorithms are:

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

Sha256withRSA

DataWeave:

%dw 2.0
import * from jwt::RSA
output software/json
---
{
	token: JWT(
		{
			"alg": "RS256",
			"typ": "JWT"
		},
		{
			iss: "jwt-rsa-demo@test.com",
			aud: 'https://check.mulesoft.com',
			iat: (now()) as Quantity { unit: 'seconds' },
			exp: (now() + |PT7200S|) as Quantity { unit: 'seconds' }
		},
		vars.privateKey as String,
		'Sha256withRSA'
    ),
    expiration: (now() + |PT7150S|)
}

Create JWT With HMAC Algorithm

  • Step 1: Add the rework message to create the JWT.

Right here, we have to cross the 4 parameters beneath to the JWT operate.

Sr. No. Parameter Datatype Description Instance

1

header

Object

JWT Header

{

       "alg": "HS256",

       "typ": "JWT"

}

2

payload

Object

JWT Payload

{

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

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

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

       exp: (now() + |PT7200S|) as Quantity { 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:

%dw 2.0
import * from jwt::HMAC
output software/json
var secretKey = "MuleJWTPassword@2023"
---
{
    token: JWT(
    	{
      		"alg": "HS256",
      		"typ": "JWT"
      	},
        {
            iss: "jwt-hmac-demo@test.com",
            aud: 'https://check.mulesoft.com',
            iat: (now()) as Quantity { unit: 'seconds' },
            exp: (now() + |PT7200S|) as Quantity { unit: 'seconds' }
        },
       secretKey as String,
      'HmacSHA256'
    ),
    expiration: (now() + |PT7150S|)
}

Step 4

Set off the request and it’ll generate JWT.

{
    "token": "eyJhbGciOiAiUlMyNTYiLCJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiand0LXJzYS1kZW1vQHRlc3QuY29tIiwiYXVkIjogImh0dHBzOi8vdGVzdC5tdWxlc29mdC5jb20iLCJpYXQiOiAxNjk2NDkzODQwLCJleHAiOiAxNjk2NDk3NDQwfQ.q50ao_-1_ke7ZIizZYgz_914q8JcISWk8uCC0h08FtzlUJYWU0ss7M0gtBJSnDa3e1hAsJ2MlmKhVjL7wXbkYNRVtdCk6N1RC6dEJ2xLOPKMObvcSHvt9e5sTWOPqCBW4sZOQm9xMkCqWqkHAJ5wZzvDGOlo7K0I-23b2AhqESDqVGXNXdWKvgwVGtH1okL7PKy9aQw7grJ9iB6iV_yaFgGX82gu0m1QilF83VHvAy7sWq7RYk54FmI09U45-CXYtX_tpaq3Y1vjaGjHmkKqPfJnqO4ysBiRICvxhRcRqQgONqUSu7YpV59JoUG66r2ONnS9NFJXQSBVq7-GQl0g4A",
    "expiration": "2023-10-05T14:46:30.505+05:30"
}
{
    "token": "eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiand0LWhtYWMtZGVtb0B0ZXN0LmNvbSIsImF1ZCI6ICJodHRwczovL3Rlc3QubXVsZXNvZnQuY29tIiwiaWF0IjogMTY5NjQ5MzIzOSwiZXhwIjogMTY5NjQ5NjgzOX0.sAiK-Bto_8JS4WLJa3nFoSYCIIv3IiXYLyL0QKXB-hQ",
    "expiration": "2023-10-05T14:36:29.62+05:30"
}

Validation

  • Validate RSA JWT utilizing public key:
  • Validate HMAC JWT utilizing a secret key:

Limitations

DataWeave JWT Library doesn’t assist encrypted personal keys to generate JWT utilizing the RSA algorithm. If the requirement is to create JWT utilizing the RSA algorithm with an encrypted personal key, you should utilize both customized Java code or JWT Signal Module.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version