In this tutorial, we will demonstrate a step by step to decode JWT Token in Mule 4 using Invoke static connector and this example also includes the validation of signature with private key.
What is JSON Web Token?
JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between the two parties.
JWT are an important piece to ensure trust and security in your application. JWT allow claims, such as user data, to be represented in a secure manner.
Why JSON Web Token?
JWT make a compelling case for using JWTs to authenticate and authorize access to APIs. Few of JWT features are:
Decode JWT Token in Mule
Now let’s see how to validate the JWT signature with private key and also decode the JWT Token to JSON format.
Step 1: Add the below dependencies in your project pom.xml file.
<dependency> <groupId>com.googlecode.jsontoken</groupId> <artifactId>jsontoken</artifactId> <version>1.0</version> <dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> <dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.6.0</version> <dependency> <dependency> <groupId>com.nimbusds</groupId> <artifactId>nimbus-jose-jwt</artifactId> <version>9.7</version> <dependency>
Step 2: Create a package (com.vanchiv) and then create a new Java class called AuthHelper under the same packge.
Step 3: Create a sample project with HTTP Listener as source and configure accordingly.
Step 4: Add Invoke static connector and configure as follows
Args: We will need to pass two arguments -> token and SIGINING_KEY. Where token is the JWT and the SIGINING_KEY is the private key.
Method: verifyToken(String token, String SIGNING_KEY) (verifyToken(java.lang.String,java.lang.String))
There are two methods. One is to create JWT and another one is validate the token.
Step 3: Add a logger component to print the decoded payload and handle the different errors such as Signature verification failed, Token expired, etc.,
The mule flow would look like:
That’s simple! Now let’s test the mule application.
Here is our sample JSON Web Token. You can get a sample token from https://www.jsonwebtoken.io/ and the private key is secret.
Scenario #1: Pass valid JSON Web Token.
Scenario #2: Pass a valid JSON Web Token and invalid Private key.
That’s it!. We are able to validate the signature with private key and also decrypt the JWT using custom Java class.
We hope this tutorial helped you to understand how to use custom Java class to work with JSON Web Tokens.
If you want to generate a JWT Token then you can use another method to create. Please do let us know in the comment section, In case if you face any difficulties to generate JWT.