In this blog, we will learn about JWT, its basic structure, advantages and how can we generate and validate JWT in java.
So, Authentication is the process of verifying the identity of a user, and JWT is a safe way for transferring information between multiple parties in the JSON format. So for example, If you want to login to any application say XYZ that allows you to log in via your email(Gmail), then the application contacts Gmail Authentication service which verify the user and generates a JWT that allows you to access XYZ application. Now coming to the technical aspects of JWT.
What is JWT?
It stands for JSON Web Token which is an open standard for creating access tokens that can verify the integrity of the claims. For Example, the authentication server generates a token that has the claim “logged in as admin” and provide that to the client. Now that token can prove that the user is logged in as admin while making API calls to the application server.
Structure of JWT
JSON web token consists of three parts:-
and each part is separated by the dot.
Let’s discuss each part in detail.
The header consists of two parts:
1. Which signing algorithm to be used, and
2. The type of token(JWT).
Basically, signing can be done on the basis of a secret key or a public and private key.
The Payload part consists of the claims. Claims are the statements about the user and some additional data. There are standard claims which can be found here and even we can create customized claims also. They are further divided into three parts that are Registered, Public and Private.
For the Signature part, what we want is the Header and payload in the encoded form, secret and we get the Signature in the following manner.
HMACSHA256(base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)
By combining all the three “header, payload, and the signature”, we get a JWT token i.e.
const token = base64urlEncoding(header) + '.' + base64urlEncoding(payload) + '.' + base64urlEncoding(signature)
Example: code snippet that generates and validateS the JWT token in Java.
//Generating the JWT
|.signWith(HS512, new SecretKeySpec(parseBase64Binary("Bhawna"), HS512.getJcaName()))|
|.setExpiration(addSeconds(new Date(), 80))|
//Validating the JWT
|.setSigningKey(new SecretKeySpec(parseBase64Binary("Bhawna"), HS512.getJcaName()))|
Advantages of JWT
- JWT is the self-contained token with all the user details and authentication.
- It is stateless, so no need to maintain the session.
- JWT is decoupled in nature which means that token can be generated anywhere either in the separated server or in the resource server.
- JWT also gives good performance due to less network roundtrip.
Hope this is helpful. Please feel free to provide your suggestions 🙂