JSON Web Token: 8 Easy Steps to Understand and Implement JWT
- In Programming
This article is going to be a complete information about the JSON Web Token. If you find JWT hard, difficult to grasp, and just want an easy answer to the question “What the heck is JWT?” then this article is for you.
This article is going to be a complete answer to all your questions.
The entire article is divided into sub-parts for easy understanding. The eight-step approach will help you to understand better.
Before you start, why not take a small pause and tweet about it 😉
Tweet and tell the world that you are going to learn about JWT in-depth 😉I'm about to learn JWT in-depth. Check out the source of information. #BeMyAficionado Click To Tweet
Summary of all the topics that I’m going to cover in this article are as follows:
# What the heck is JWT?
In this topic, you will learn the JWT Concepts and its schema. How information is stored and structured? You will learn in-depth about the significance of each property defined in JWT.
# How JWT works? What is the entire process?
You will learn about the entire process and lifecycle of JWT. From its very creation to its validation. I will give you an in-depth view of the entire process required to validate the user.
# What is JWT Header? What information does it hold?
Everything you need to know about the Header part of the JWT schema is wrapped up in this section. What information does it carry? What is the significance of the information carried by the token? and a lot more.
# What is Payload? What is the Significance of the Payload in JWT?
In this topic, you will learn about the second part of JWT called Payload. How can you use the Payload part to send custom user information safely through space?
# What is JSON Web Signature
Signature is the third and final part in the making of a JWT token. This part of the JWT is used to validate whether the sender of the packet is authentic or not.
# How does JWT protect our data?
You will see that the purpose of JWT is not to hide or obscure user’s data in any way. The main purpose of JWT is to prove the authenticity of the source. It makes sure that the data which is being sent is coming from an authentic source.
# How to verify JWT Token?
This will be the last step of the process where you will learn how to verify the token at your end. Here, we will make use of the JWS part to check whether the source of information is authentic or not.
# Essentials for validating a token
I will tell you about the claims with which you can make sure that the token is authentic. There are more than one ways to check for token authenticity but there is one standard way and that is what we will discuss.
# Implement JSON Web Token
The most exciting part of this post. In the end, I will show you how JSON Web Token can be implemented in your application. I will be using JAVA for this purpose because of its familiarity but the same could be implemented with any language.
If I get too crazy or technical in the post, do tell me in the comments. I promise I will improvise 😀
Let’s quickly dive into the detailed section below.
What the heck is JWT?
JSON Web Token (JWT) pronounced as (jot) is a standard way of safely passing information (claims) in space-constrained environments.
A JSON Web Token looks like this:
Okay… my expressions were exactly the same when I first saw that jibberish.
But, it’s not jibberish. It is full of deep meaning and context :p
What’s amazing about this jibberish text is that it is compact, concise and holds information which is necessary to authenticate the sender.
Let’s get into details…
Try to look at the token closely and you will see 3 dots (period) that separates its three parts i.e. Header, Payload, Signature. Take a look at the below token (newlines inserted to separate each part).
The first part of the period is JWT Header. This part holds the claims about itself.
Just like you must know a few things about yourself (name, the language you speak, origin) before opening a conversation with anyone. Similarly, JWT header holds the algorithm used to encrypt the information and the type of token which is being used (JWT).
By reading the header, the receiver will know how to interpret the entire token.
Below is the un-jibberish version of the above jibberish :/
Second Part of JWT
The second part of the token after the period is called JWT Payload. This is the data part of JWT. The payload is used to store data which will be sent to the destination. This is often the heaviest part (in terms of size) of JWT as it contains user-defined claims.
Below is the actual information passed in as a payload.
The third part is the signature also know as JSON Web Signature (JWS) This part is responsible for maintaining the authenticity of the sender. JWS comprises of a secret key which is pre-exchanged between the sender and the receiver of the packet. I have talked about the entire process in the later sections.
I hope I have not gone too technical with my language. Maybe I’m too concerned about my writing :/ Huh!
Well, let’s dive a little deeper.
The header part of the token:
Okay, here I’m going to repeat the definition from the previous paragraph (please don’t go away).
The Header is the very first part of the JWT token. It carries the claims about itself – meaning – the header consists of the claims that explain whether the token is encrypted or not and which algorithm is used to sign the token. It is required to successfully parse the token and validate it.
The claims of the header vary according to the type of JWT token. For example – In encrypted JWTs, it is mandatory for the header to carry the information about the type of cryptography algorithm used and how the content of the token has been encrypted.
Claims in JWT Header
In unencrypted JWT token, there is one mandatory claim and that is the
- alg: The algorithm which is used for signing or decrypting the algorithm.
The Header also contains other optional claims as well. The two other claims are typ and cty claims:
typ: This stands for the type of token being sent. It may be used to tell the type of the media content that is being sent in the JWT token.
There are times when you might use JWT to send some other content. How are you going to intimate this to the receiver?
Exactly, typ is the claim to look for.
It is used when JWT carries values which are not JWT. These values are intended to be used by the JWT application to disambiguate a different kind of objects that might be present in the application data structures. For a more detailed view, follow this link. However, that is a rare case scenario. Usually, the value of typ is set to JWT.
cty: This claim is for the content type that caries structural information about the JWT. It is used to provide the extra information for the JWT token. For example, if you are sending a nested JWT token inside a JWT token then this parameter will be set to JWT. By setting the value of this parameter as JWT, you are telling the application that a nested JWT has been used with the token.
This is again a rare case and its use is not recommended in most cases. You should not use this claim unless required.
You can also add custom user-defined claims in the header section.
However, it should only be done if you are sending some custom claim in the payload that requires further processing logic or implementation details. You know what I mean (if not then comment below :D)
A payload part of a JWT token:
This is the second part of JWT. The part that carries information. This is the part where user data is defined along with other pre-defined specs.
The good news… No field in the payload is mandatory.
However, there are a few pre-defined standard specs that need to be populated as per the standards.
As you can see in the above image, I have used name and admin as custom user-defined claims. The data it holds is specific to each user and could be used to identify the user when it sends the request.
All the other claims (aud, iss, exp etc…) are pre-defined specs of JWT and hold a definite definition. Such claims are known as registered claims. Their meaning is already well established and registered. Let’s take a look at all of them.
From the word issuer.
It is a case-sensitive string or URI that uniquely identifies the user or the party who issued the JWT.
The thing that needs to be understood here is that the interpretation of the data is application specific and there is no central authority which manages the issuer.
You will understand the entire thing once you reach the implementation part of the token.
From the word subject.
A case-sensitive string or URI that uniquely identifies the party that this JWT token carries information about.
In other words, the claims contained in the JWT are statements about this party. The JWT specs specify that these claims should be unique in the context of the issuer or, in cases where that is not possible, it should be globally unique.
Handling of the claim is application specific.
From the word audience.
Identify the intended audience of this token with the use of this claim.
The simplest use of this claim is to check whether the audience mentioned in the token is identified with the party reading it. If the party fails to identify itself with the audience mentioned in the token, then the entire token must be discarded.
This claim is also application specific.
From the word expiration (time).
This claim is a number field that holds the exact time in Unix Timestamp (seconds since the epoch)as defined by POSIX. The time after which the token must no longer be used.
This time is provided by the creator of the token and it is intended to protect the data from unauthorized access. The exp time should not last for more than a few minutes unless the purpose of the JWT is different.
From not before time.
This claim also holds a numeric value. However, this is the exact opposite of exp. The difference between exp and nbf is that it tells the exact moment from which the token must be considered valid. The use of this field is again dependent on the application’s logic to handle.
From issued at (time).
It is a number representing the time in the exact same format as exp and nbf. It holds the value of the time when it was first issued by the issuer.
from JWT ID.
Differentiate JWTs with other similar content with the help of this claim (preventing replays for instance). The implementation is guarantees the uniqueness.
As you may have noticed that the names of all the claims are short. JWT standards are the reason behind that compactness.
Shortness and Compactness is the essence of JWT.
You will achieve better results if you will stick to the standards. Create short and compact JWT tokens to ease the entire process for both the parties (issuer and issuing party).
JSON Web Signature
You have so far learned about the Header and the Payload part of the JWT token.
And so far we have used JWT to only send unencrypted information through space.
Have you thought about the authenticity of the sender?
Have you wondered, what would happen if some intruder replaced your information with something suspicious?
Well, there is no way to identify the authenticity of the token without a Signature.
The receiver will never know whether the information that it has received has come from an authentic source or not.
Therefore, you must send something special and unique to the receiver with the help of which the receiver can identify that the token has been sent from the intended source.
What I’m trying to say is that the receiver of the token has no clue whether the token is being sent from the authentic source or not. There is no way to find out the authenticity of the JWT without having some kind of signature or validation mechanism. That is where the third part of JWT comes into the picture. It provides a way to validate the authenticity of the token. (I think I have stated the same thing many times :p)
Real Life Scenario
Suppose I have to send a piece of information to you through space. Space which is filled with intruders. Intruders who can manipulate the very nature of the information.
Let’s assume that the information is not sensitive but the accuracy of that information is important.
How are you going to validate if the information that you have received is exactly the same that I sent you in the first place?
In other words, How can you validate the authenticity of the information?
The Signature part of JWT is the answer to this question.
Now, before sending the information through space, I will make sure to sign it with a special signature. The signature which can only be reproduced by the person who has the SECRET KEY
How did the SECRET KEY come into the picture?
Before sending information through space, we will be meeting in person and create a SECRET KEY. This secret key will only remain with you and me. Nobody else will have any knowledge of the secret key.
Now, I will create a signature by applying the certain algorithm on the information itself by using that SECRET KEY. I will send the algorithm to you along with the information.
Once you receive the information, you will read the algorithm and apply the same algorithm to create a similar signature at your end. You will match your Signature with the one I sent you. If the Signature matches that means the information has not been altered or tampered, otherwise you will discard the information and not believe anything that I said.
Simple. Isn’t it?
The process of checking the Signature is called validation or validating the token.
Signature is not the only thing that plays role in the validation of the token. Along with the signature, the claims of header and payload must also be checked for the authenticity of the token. The claims such as exp and aud must be checked before accepting the token.
How to create a Signature of a JWT?
This is how a signature looks like:
And, this is how it is created:
As you can see in the above image, creating a Signature is a 4 step process.
- Encode the header with URL Friendly Base64 Encoding.
- Encode the Payload with the URL Friendly Base64 Encoding.
- Append both The Header and The Payload with a “DOT” in between.
- Hash The appended Header and Payload with a secret key using HMACSHA256 algorithm (also called HS256).
The resulting string will be the signature of the JWT:
Here, is the complete structure ofa JWT token,
I hope it has started to make sense now. How the JWT token is used to transmit information and how you can validate the authenticity of the token.
Here’s the schematic diagram that explains the compact serialization process of creating a JWT token:
That is the whole process for creating JWT token signed with a secret key.
How JWT protect our data?
It is very important to understand here that JWT was not meant to protect data in any way. It does not hide or obscure data in any way. Authentication is the main purpose of a JWT token.
Information can be retrieved easily by anyone who has access to the token unless the information is encrypted (requires additional application logic).
In an unencrypted JWT token, the information is only encoded and signed, it is not encrypted in any way. So, if anyone got access to the token, he/she can simply decode the header and payload using the Base64Decode algorithm and retrieve the information as it is. However, there are other ways to encrypt data that is being sent in the payload.
JWT was not meant to carry sensitive data. It is just a replacement of a stateful verification process where we used to store user’s identifier in the clients’ browser in the form of cookies.
JWT does not guarantee any security of the data. Security aspects are supposed to be handled by the application implementing JWT.
Use Encrypted JWT for Security
One way of encrypting the JWT is to create a nested encrypted JWT.
If you remember the cty -> Content-Type claim in the header. It is responsible for indicating that the JWT token consists of another JWT token. So, once the user receives a JWT token, it will validate the token and read the CTY claim present in the header part of the parent JWT. With the help of that claim, the receiver will understand that it contains an another JWT as a payload.
The header of an encrypted JWT represented as:
The enc claim tells that the JWT has been encrypted using the A128CBC_HS256 algorithm. You have the secret key in your possession safely. So, you can use this algorithm along with your secret key to successfully reverse the process and decrypt the data.
The validation of this token will be done by validating the signature. Only if the signature is valid, the user will move on to the payload part where the nested JWT is stored.
The final encrypted token will look like the one below (new line inserted for readability):
By sending nested JWT token, you can be sure that the information will be obscured from the intruder. Even if the intruder manages to get the token, he will not be able to read the data as the data is in the encrypted format. And the key to that encryption is safe with you.
Essentials For Validating the Token
The signature is not the only thing that must be validated before accepting the token. There are other claims as well that needs to be validated before successfully validating the token.
Before moving on to the final implementation part of this guide. I want to quickly explain you about the essentials for validating the token.
Before granting the access to the user, you must check below-mentioned fields for token validity:
- exp (expiration)
- iss (issuer)
- aud (audience)
I have already told you about the meaning of these claims which are present in the payload of a token. So, let’s quickly see how these payloads are used to validate the token.
The date/time listed in the exp claim (UNIX timestamp) must be before the current date/time.
Here’s what you need to do:
- Find the current UNIX Timestamp in seconds.
- Compare the exp value with the current UNIX Timestamp.
- If the current timestamp is greater than exp time then the token has been expired and must be rejected.
Check if it is this the valid issuer of your endpoint. The issuer must be from the one configured in your API.
Here’s what you need to do:
- Fetch the issuer present in the iss claim.
- Check it in the list of the valid issuer from your database or according to your application logic.
- If the issuer is not found in the list of valid issuer then you must reject the token without further processing.
This claim identifies the recipients that the JWT is intended for. By Auth0 standards, aud claim holds the unique identifier of the target API (field identifier in your API Settings). If API is not intended audience then reject the request.
The steps are similar to the one you performed to validate issuer.
Implementation of JWT Token Using JAVA
We have covered almost all aspects of JWT token. Now, let’s start the final section of this guide. In this section, you will be implementing JWT token using JAVA language.
Before we move on, I want you to know that JWT token is not limited to any language. JWT is a standard and can be implemented with any available technology. I’m using java to implement JWT because it is one of the most popular languages and an industry standard.
I have created a small JWT Demo to show you how you can implement JWT in your project.
The JWT service is responsible for generating the JWT token and validating it.
Let’s start with the first step of creating the project.
Create a simple SpringBoot Project to implement the JWT Demo. You can implement it using a simple Java project as well.
# Create a new Gradle Project and paste the below dependencies into it.
(Do not know about Gradle, read this introductory article).
I have included the
io.jsonwebtoken dependency. This dependency loads the required JAR(s) into your project’s classpath that is required to create a JWT token.
compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.0'
The above dependency provides all the necessary methods to create a JWT token. You just have to call the required methods to create different portions of JWT such as (Header, Payload, Signature).
# Create JWTService class with below code:
Here is the code for the JWT Service. I want you to check out the
validateToken() method of the
JWTService class :
Look at line number #29 of JWTService class. #29 is the line which is responsible for creating the third portion of the JWT i.e. Signature. Also, you can see that I have used SignatureAlgorithm HS256 to create the signature.
This token is an unencrypted token in which the user can easily retrieve the information from the token. This type of token is only used to authenticate the authenticity of the sender. It should not be used to send sensitive information over the network.
With the last part covered i.e. the implementation part, it is time to conclude the post. I hope you have understood every aspect of JWT token explained in this article.
I have tried my best to explain the various parts of JWT and how you can use JWT in your project.
Here’s the BlackBoard Style summary of the entire topics that we covered in this post:
Please share the post as a tribute to BMA. A simple tweet will work 🙂I just learned everything about a JWT Token. Here's the link to the post. #BeMyAficionado Click To Tweet
I will keep on creating such posts in the future, do not forget to subscribe to BMA to receive an absolutely free handbook on backing up your WordPress website free of cost.
We are working on something interesting that you would want to be a part of.
So, stay in touch and keep blogging.