What are Json Web Tokens or JWT ?

Shavindi Pathirana
Jun 30 · 2 min read

When to use JWT?

Authorization: This is the most common use of jwt. Everytime a user is logged in to the system, a token is generated to the subsequent user. This permits the user to have access to use the routes, services, and resources whenever he needs.

Information Exchange: JWts are a great way of securely transmitting data between two parties. As the jwts can be signed, for example using public/private keys of each user it is possible to identify whether the senders are people who they say they are. As the signature is calculated using header and a payload it is possible to verify that the content hasn’t been tampered with.

What is the JWT structure?

JWT consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.

header.payload.signature

Header

Headers consist of type of token which is JWT, and the hashing algorithm such as HS256, HMAC, SHA256 or RSA.

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

Then, the above JSON is Base64Url encoded to form the first part of the JWT.

Payload

Payload contains claims which are the information about the entity

The JWT specification defines seven claims that can be included in a token. The registered name claims are:

  • iss
  • sub
  • aud
  • exp
  • nbf
  • iat
  • Jti

You can also use private name claims which is used to convey identity related info such as name or category. When naming these, it is necessary to avoid name collisions because public and private claims are not registered.

An example of payload could be:

{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}

The payload is then Base64Url encoded to form the second part of the JSON Web Token.

Signature

This is made using the encoded headeer, encoded payload, secret, the algorithm specified in the header, and sign.

The below signature is created using the HMAC SHA256 algorithm.

HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

You can use https://jwt.io/ whenever you want to check jwt tokens and see the connection between the header, payload, and the isgnature.

Encoded and decoded Json Web Token

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade