top of page
Writer's pictureShiva Sahu

JWT token creation using DataWeave



 

In this post:

 


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.



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.



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 DataWeave 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



2,686 views0 comments

Comments


bottom of page