JWT Token Creation Using DataWeave

Author: Shiva Sahu

Security implementations have been revolutionary through OAuth 2.0, OpenID Connect, SAML, etc. OAuth 2.0 and OpenID connect mostly use JWT as a token format. JWT is a very familiar term for the API fraternity.

There are instances where we need to create a JWT token to authorize our APIs to a service or authorize any client if we are using any custom solutions for authentication/authorization.

Let’s take a deeper look at JWT tokens.

Sample JWT token

ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIiwKICAia2lkIjogIjEwMSIKfQ.ewogICJpc3MiOiAiR1RBIiwKICAiaWF0IjogMTY1NjQyMTQ0NiwKICAicmVxdWVzdGVkU2NvcGUiOiBbCiAgICAieG90cCIKICBdCn0.l2slJ86T7J3at9UG5esKMi5B9h02WjcpIuMZm_5mxzM

Let’s see the basic structure of this token. (Visit https://jwt.io/#debugger-io)

As you can see in the image, the token is decoded into three parts, 

  1. Header (ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIiwKICAia2lkIjogIjEwMSIKfQ)
  2. Payload (ewogICJpc3MiOiAiR1RBIiwKICAiaWF0IjogMTY1NjQyMTQ0NiwKICAicmVxdWVzdGVkU2NvcGUiOiBbCiAgICAieG90cCIKICBdCn0)
  3. Signature (l2slJ86T7J3at9UG5esKMi5B9h02WjcpIuMZm_5mxzM)

We will see in the following topic how to create this token.

How to create JWT using Java

There are multiple libraries to do this in JAVA: I always try to use the simplest code.

https://gist.github.com/jacktravenk123/f046643dae96d061eb4cc01b47b8af74

The token generated:

eyJraWQiOiIxMDEiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJHVEEiLCJyZXF1ZXN0ZWRTY29wZSI6WyJ4b3RwIl0sImlhdCI6MTY1NjQyMjk3Nn0.3kM0_DUuJCIig2OlyqxqnjODUxRvTA93d9Tgu-ZhOgw

Let’s decode this token

How to create JWT using DataWeave

JAVA seems to be very technical. Let’s switch to our magical language.

https://gist.github.com/jacktravenk123/f19283ae4a9ff4dbe17b0df442835e3d

The token generated:

ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIiwKICAia2lkIjogIjEwMSIKfQ.ewogICJpc3MiOiAiR1RBIiwKICAiaWF0IjogMTY1NjQyMjk3NiwKICAicmVxdWVzdGVkU2NvcGUiOiBbCiAgICAieG90cCIKICBdCn0._RUefLwi3UBP7jbxE7VHB-t-aMmCNdvFSr7frgW7wNY

Let’s decode this token:

Voila, you are done. TBH, it’s way more fun to code in DataWeave.

The tokens generated from the JAVA class and dwl get decoded to the same data. 

Summary

JWT is vital in today’s API world. It’s not enough to just know the code; we need to focus on the security of API from all perspectives. 

References

We use cookies on this site to enhance your user experience. For a complete overview of how we use cookies, please see our privacy policy.