Understanding JWT Tokens: A Comprehensive Guide

Hemin PanchalHemin Panchal
4 min read

Introduction

In the ever-evolving landscape of web development and cybersecurity, ensuring secure and efficient communication between clients and servers is paramount. One tool that has gained significant traction in this realm is JSON Web Tokens (JWT). If you're new to JWT or looking to deepen your understanding, this guide will walk you through what JWT tokens are, how they work, and why they are beneficial.

What is a JWT?

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

Structure of a JWT

A JWT is composed of three parts separated by dots (.):

  1. Header

  2. Payload

  3. Signature

1. Header: The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

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

This JSON is then Base64Url encoded to form the first part of the JWT.

2. Payload: The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

Registered claims: Predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), etc.

Public claims: Can be defined at will by those using JWTs. But to avoid collisions, they should be defined in the IANA JSON Web Token Registry or as a URI that contains a collision-resistant namespace.

Private claims: Custom claims created to share information between parties that agree on using them and are neither registered or public claims.

An example payload might look like this:

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

The payload is then Base64Url encoded to form the second part of the JWT.

3. Signature: To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

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

The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

How Does JWT Work?

When a user successfully logs in using their credentials, a JWT is returned to the client. The client will then send this JWT along with every subsequent request to the server. The server will then validate the JWT and grant access to the requested resources if the token is valid.

Hereโ€™s a simplified workflow:

  1. User logs in with credentials.

  2. Server validates credentials and creates a JWT.

  3. JWT is sent to the user.

  4. User stores the JWT locally (e.g., localStorage or sessionStorage).

  5. User sends JWT with each request to access protected routes/resources.

  6. Server validates the JWT.

  7. If valid, server responds with the requested resource; otherwise, it rejects the request.

Benefits of Using JWT

  1. Compact: Due to their small size, JWTs can be sent through a URL, POST parameter, or inside an HTTP header.

  2. Self-contained: The payload contains all the required information about the user, avoiding the need to query the database multiple times.

  3. Secure: When using a secure algorithm such as RSA or HMAC, the integrity and authenticity of the token can be verified.

  4. Stateless: JWTs are self-contained, making them suitable for distributed systems where session state isn't stored on the server.

Common Use Cases

  1. Authentication: JWTs are widely used for authentication purposes. After the user is authenticated, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

  2. Information Exchange: JWTs can be used to securely transmit information between parties. Since they can be signed, you can be sure that the senders are who they say they are. Additionally, the structure of a JWT allows you to verify that the content hasn't been tampered with.

Best Practices

  1. Use HTTPS: Always use HTTPS to ensure the token is transmitted securely.

  2. Use Strong Secrets: Use a strong, unique secret key to sign the tokens.

  3. Short Expiration Time: Use a short expiration time for tokens to minimize the risk if a token is compromised.

  4. Store Tokens Securely: Store JWTs securely on the client side, for example, using HttpOnly cookies.

Conclusion

JWTs provide a robust and secure method for ensuring the integrity and authenticity of data in stateless applications. By understanding the structure and workflow of JWTs, developers can effectively implement them to enhance security and efficiency in their applications. Whether used for authentication or information exchange, JWTs are a powerful tool in the modern developer's toolkit.

0
Subscribe to my newsletter

Read articles from Hemin Panchal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hemin Panchal
Hemin Panchal

I ๐Ÿ‘‰๐Ÿ‘ฅ instruct ๐Ÿ‘€computers๐Ÿ“ฒ to do โœจ Human ๐Ÿ‘ค Stuffs. And occasionally ๐Ÿถ use ๐Ÿป my computer ๐Ÿ–ฑ Degree to save ๐ŸฆŽ the world. ๐ŸŒŽ๐Ÿ™‹