What is JWT (JSON Web Token)?

Reading Time: 2 minutes

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:-
1) Header
2) Payload
3) Signature
and each part is separated by the dot.

header.payload.signature

Let’s discuss each part in detail.

 Header



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


{
"alg": "HS256",
"typ": "JWT"
}
view raw

header.txt

hosted with ❤ by GitHub

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.

Payload



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


{
"sub": "123456789
"name": "Jack",
"admin": true
}
view raw

Payload.txt

hosted with ❤ by GitHub

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.

Signature

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



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


Jwts.builder()
.setSubject("")
.signWith(HS512, new SecretKeySpec(parseBase64Binary("Bhawna"), HS512.getJcaName()))
.setIssuedAt(new Date())
.setExpiration(addSeconds(new Date(), 80))
.compact();
view raw

create_token

hosted with ❤ by GitHub

//Validating the JWT



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


Jwts.parser()
.setSigningKey(new SecretKeySpec(parseBase64Binary("Bhawna"), HS512.getJcaName()))
.parseClaimsJws(token)
.getBody()
.getSubject();
view raw

gistfile1.txt

hosted with ❤ by GitHub

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 🙂

References:
https://en.wikipedia.org/wiki/JSON_Web_Token
https://dzone.com/articles/jwtjson-web-tokens-are-better-than-session-cookies
https://jwt.io/introduction/
https://blog.bitsrc.io/understanding-json-web-token-authentication-a1febf0e15


Knoldus-blog-footer-image

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading