Explaining JSON Web Tokens (JWT) with Real-Life Examples (2024)

Shubhadeep Chattopadhyay

·

Follow

7 min read

·

Jan 18, 2024

In the ever-evolving world of web applications and security, it’s crucial to understand the concepts that underpin the mechanisms keeping our data and systems safe. One such concept is the JSON Web Token (JWT). JWTs are a fundamental part of modern web authentication and authorization systems, and this article aims to demystify them with real-life examples, making the complex simple.

Explaining JSON Web Tokens (JWT) with Real-Life Examples (2)

What is a JSON Web Token (JWT)?

A JSON Web Token, or JWT, is a compact and self-contained way to represent information between two parties securely. It is encoded as a JSON object and digitally signed. JWTs are often used for authentication and authorization, both on the client and server sides of an application.

JWTs are comprised of three parts: header, payload, and 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.

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

  • Registered claims are predefined and include information like `iss` (issuer), `exp` (expiration time), `sub` (subject), and more.
  • Public claims are defined by the JWT standard but not mandatory, and they are meant to be used in the same way as registered claims. However, you should be cautious about their usage to avoid conflicts with others.
  • Private claims are custom claims that are agreed upon between the parties involved. They should be defined in the context of your application.

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

So, a JWT typically looks like “xxxxx.yyyyy.zzzzz”

Where `xxxxx` represents the header, `yyyyy` the payload, and `zzzzz` the signature.

How Does a JWT Work?

To better understand JWTs, let’s break down their workings with a real-life analogy. Imagine you’re at a club that uses hand stamps for entry and exit. These stamps are special because they are not easy to duplicate. The club’s bouncer, the ‘Verifier,’ uses these stamps to verify your identity.

Stamp Creation: When you enter the club, the bouncer checks your ID, then uses a special stamp (the ‘Signature’) to mark your hand. The stamp contains the club’s logo and the current date and time.

Hand Stamp: This stamped hand is like the ‘Payload’ in a JWT. It contains information about your identity (the club’s member) and the timestamp.

Hand Check: When you leave the club and want to re-enter, the bouncer checks your stamped hand. They match the club’s logo, and if the timestamp is still valid (within the entry time frame), you’re allowed in. This is the ‘Verification’ process, just like the JWT’s ‘Signature’ and ‘Payload’ being verified.

Security: The stamped hand is hard to duplicate, much like the JWT’s ‘Signature.’ As long as the stamp is valid, the bouncer trusts you to be a club member. If someone tries to change the stamp, the bouncer can easily tell it’s a fake.

Now that we have a basic understanding of what JWTs are and how they work let’s explore their application with real-life examples.

1. User Authentication

JWTs are commonly used for user authentication in web applications. When a user logs in, the server creates a JWT token and sends it back to the client. The client then includes this token in subsequent requests to access protected resources. Here’s how it works:

Scenario: You’re building a social media application where users can create and share posts. You want to ensure that only logged-in users can create posts.

Implementation:

1. User Login: When a user logs in, the server generates a JWT containing the user’s ID and some other claims. This JWT is then sent to the client.

2. JWT Usage: The client stores the JWT securely (usually in a cookie or local storage). When the user creates a post, the client includes the JWT in the request headers.

3. Server Validation: The server receives the request and validates the JWT. It checks the signature to ensure it hasn’t been tampered with and that it’s not expired. If everything checks out, the server knows the user is authenticated and allows them to create the post.

4. User Logout: When the user logs out or the JWT expires, the client discards the token. This ensures that even if an attacker gets hold of the expired token, they can’t use it to perform actions on behalf of the user.

This way, JWTs help in securely managing user authentication and authorization, allowing only authorized users to access specific resources.

2. Single Sign-On (SSO)

JWTs are also used in Single Sign-On systems, where a user can access multiple applications using a single set of credentials. Let’s consider a corporate environment where employees can access various internal tools.

Scenario: In your organization, you have multiple internal tools like email, project management, and HR systems. You want to implement Single Sign-On to streamline access for your employees.

Implementation:

1. Login to SSO Provider: When an employee logs in to the SSO portal, the SSO provider authenticates them and generates a JWT containing their user information.

2. Accessing Internal Tools: Now, when the employee accesses any internal tool, the SSO provider includes the JWT in the request to that tool.

3. Tool Verification: Each tool independently verifies the JWT. If the signature is valid and the claims indicate that the user is authorized to access the tool, the user is allowed in.

This simplifies the user experience by eliminating the need for multiple logins and ensures that the user is authenticated across different applications within the organization.

3. Reset Password Links

JWTs are also handy when creating reset password links that expire after a certain time. Consider the following example:

Scenario: In your email application, a user requests a password reset link. You want to ensure the link is only valid for a limited time.

Implementation:

1. Request for Password Reset: When the user requests a password reset, your server generates a JWT containing the user’s ID and an expiration time (e.g., one hour in the future). This JWT is sent in a link to the user’s email.

2. Link Verification: When the user clicks the reset password link, the server validates the JWT. It checks the expiration time and the signature. If the JWT is valid and within the time limit, the user is allowed to reset their password.

3. Security and Expiry: This mechanism ensures that the password reset link is secure and that it becomes invalid after the specified time.

In all these scenarios, JWTs offer a secure and convenient way to manage authentication and authorization, making it easier to control access to resources and ensuring that only authorized parties can perform specific actions.

While JWTs are a versatile and efficient solution for authentication and authorization, they come

with certain security considerations that developers must be aware of:

1. Token Storage

JWTs should be stored securely on the client side. Storing them in cookies with the `HttpOnly` and `Secure` flags set is a recommended practice. This makes it harder for malicious scripts to access the token.

2. Token Expiry

Tokens should have a limited lifespan. The `exp` (expiration time) claim helps mitigate the risk of an attacker obtaining a token with indefinite validity.

3. Token Revocation

If a JWT is compromised or a user logs out, there should be mechanisms in place to invalidate or revoke the token. Token revocation lists (blacklists) can be used for this purpose.

4. Payload Size

Keep the payload of the JWT small. Larger payloads increase the size of each request, which can impact performance. Sensitive data is best stored on the server side.

5. Secret Management

The secret used to sign tokens (in HMAC algorithms) or the public key (in RSA algorithms) should be kept secret and securely managed. Leaking this secret could lead to security breaches.

6. Algorithm Choice

Choose a secure signing algorithm. HMAC SHA256 or RSA are common choices. Avoid insecure algorithms, and stay updated on best practices.

JSON Web Tokens (JWTs) have become a staple in modern web application development, providing a versatile and secure method for handling authentication and authorization. By understanding the three key components of JWTs — header, payload, and signature — and how they are used in various real-life scenarios, you can implement robust authentication and authorization systems for your applications.

Just like the stamp you receive at the club, a JWT serves as a trustworthy credential that enables secure access to specific resources or services. However, it’s essential to be aware of potential security concerns and best practices to ensure that JWTs fulfill their purpose effectively.

As you continue to explore the world of web security and authentication, consider how JWTs can be a valuable tool in your toolkit, helping you create robust and user-friendly applications while safeguarding sensitive data and resources.

To stay updated with the ever-changing world of APIs, Microservices, and Digital Transformation please follow me on LinkedIn and Twitter.

You can Connect me on LinkedIn

You can follow me on Twitter

Buy me a Coffee

Are you ready to unlock the doors to your dream tech job? Whether you’re a seasoned programmer or just starting your coding journey, our comprehensive Coding Interview Courses are designed to catapult you to success in the competitive world of tech interviews.

Checkout the following links

Explaining JSON Web Tokens (JWT) with Real-Life Examples (2024)
Top Articles
It Would Cost $538,000 To Buy Everything On Steam
Unlike Other Margin Exchanges, PrimeBit Users Can Withdraw Crypto Immediately | NewsBTC
Jail Inquiry | Polk County Sheriff's Office
Victor Spizzirri Linkedin
Research Tome Neltharus
Fort Carson Cif Phone Number
Brgeneral Patient Portal
Konkurrenz für Kioske: 7-Eleven will Minisupermärkte in Deutschland etablieren
WK Kellogg Co (KLG) Dividends
Craigslist/Phx
Our Facility
Slushy Beer Strain
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Craigslist Pets Longview Tx
Who called you from 6466062860 (+16466062860) ?
Sony E 18-200mm F3.5-6.3 OSS LE Review
Michael Shaara Books In Order - Books In Order
Icommerce Agent
Las 12 mejores subastas de carros en Los Ángeles, California - Gossip Vehiculos
Project, Time & Expense Tracking Software for Business
Espn Horse Racing Results
Lakewood Campground Golf Cart Rental
Ups Drop Off Newton Ks
Gina Wilson Angle Addition Postulate
6 Most Trusted Pheromone perfumes of 2024 for Winning Over Women
Inkwell, pen rests and nib boxes made of pewter, glass and porcelain.
Dr Seuss Star Bellied Sneetches Pdf
Doctors of Optometry - Westchester Mall | Trusted Eye Doctors in White Plains, NY
Does Royal Honey Work For Erectile Dysfunction - SCOBES-AR
Top Songs On Octane 2022
Ravens 24X7 Forum
47 Orchid Varieties: Different Types of Orchids (With Pictures)
Wake County Court Records | NorthCarolinaCourtRecords.us
Appraisalport Com Dashboard /# Orders
Dreammarriage.com Login
Free Robux Without Downloading Apps
Terrier Hockey Blog
Empire Visionworks The Crossings Clifton Park Photos
Greater Keene Men's Softball
The TBM 930 Is Another Daher Masterpiece
9 oplossingen voor het laptoptouchpad dat niet werkt in Windows - TWCB (NL)
How Does The Common App Work? A Guide To The Common App
Devon Lannigan Obituary
Hanco*ck County Ms Busted Newspaper
Centimeters to Feet conversion: cm to ft calculator
Avance Primary Care Morrisville
Join MileSplit to get access to the latest news, films, and events!
Marine Forecast Sandy Hook To Manasquan Inlet
Definition of WMT
Autozone Battery Hold Down
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated:

Views: 6369

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.