Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
JSON Web Token (JWT)
Next article icon

JSON Web Token (JWT)

Last Updated : 24 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps and APIs to protect against unauthorized access.

The data in a JWT, such as user details, is stored in a simple JSON format. To keep the data safe, the token is signed cryptographically, making sure that no one can alter it. The signing can be done using these cryptographic methods:

  • HMAC (Hash-based Message Authentication Code)
  • RSA or ECDSA (Asymmetric cryptographic algorithms)

JWTs are primarily used for authentication and secure data exchange in web applications and APIs.

How JWT token Works?

  1. User Logs In: The client (browser) sends login credentials to the server.
  2. Server Generates JWT: If credentials are valid, the server creates a JWT containing user data and signs it with a secret key.
  3. Token Sent to Client: The JWT is sent back to the client and stored (usually in localStorage or a cookie).
  4. Client Sends Token in Requests: For protected routes, the client includes the JWT in the Authorization header (Bearer Token).
  5. Server Verifies and Responds: The server verifies the token, extracts user info, and processes the request if valid.

What are Tokens and Why Are They Needed?

Tokens are used to securely transmit sensitive information between the client and the server. Instead of sending plain data (e.g., user info) that could be tampered with, tokens provide a secure method of validation. JWTs are widely adopted because they are tamper-proof, ensuring that data remains unaltered during transmission.

JWT Structure

structure_of_a_json_web_token_jwt_
Structure of a JWT

A JWT consists of three parts, separated by dots (.)

Header. Payload. Signature
  1. Header: Contains metadata about the token, such as the algorithm used for signing.
  2. Payload: Stores the claims, i.e., data being transmitted.
  3. Signature: Ensures the token's integrity and authenticity.

1. Header

The header contains metadata about the token, including the signing algorithm and token type here metadata means data about data.

{
"alg": "HS256",
"typ": "JWT"
}
  • alg: Algorithm used for signing (e.g., HS256, RS256).
  • typ: Token type, always "JWT".

Base64Url Encoded Header

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

2. Payload

The payload contains the information about the user also called as a claim and some additional information including the timestamp at which it was issued and the expiry time of the token.

{
"userId": 123,
"role": "admin",
"exp": 1672531199
}

Common claim types:

  • iss (Issuer): Identifies who issued the token.
  • sub (Subject): Represents the user or entity the token is about.
  • aud (Audience): Specifies the intended recipient.
  • exp (Expiration): Defines when the token expires.
  • iat (Issued At): Timestamp when the token was created.
  • nbf (Not Before): Specifies when the token becomes valid.

Base64Url Encoded Payload

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9

3. Signature

The signature ensures token integrity and is generated using the header, payload, and a secret key. In this example we will use HS256 algorithm to implement the Signature part

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

Example Signature:

SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

4. Final JWT token

After all these steps the final JWT token is generated by joining the Header, Payload and Signature via a dot. It looks like as it is shown below.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Security Considerations

  • Use HTTPS: Prevent man-in-the-middle attacks by transmitting JWTs over HTTPS.
  • Set Expiration Time: Prevent long-lived tokens that can be exploited.
  • Use Secure Storage: Store JWTs securely (e.g., HttpOnly cookies instead of local storage).
  • Verify Signature: Always validate the token's signature before trusting its content.

Implementing JWT in a web application

1. Code to create a JSON web token

This code generates a JWT (JSON Web Token) using the jsonwebtoken library in Node.js. The token contains user data and is signed with a secret key for security.

Command to install jsonwebtoken library in NodeJS

npm install jsonwebtoken
JavaScript
const jwt = require('jsonwebtoken'); const secretKey = 'abcde12345';  const token = jwt.sign({   id: 1,   username: 'GFG' }, secretKey, { expiresIn: '1h' });  console.log(token); 

Output

Screenshot-2025-02-21-094110
Code to create a JSON web token


  • Importing JWT Library: The jsonwebtoken module is required to create and verify tokens.
  • Defining Secret Key: A secret key (abcde12345) is used to sign the token securely.
  • Creating JWT: The jwt.sign() method generates a token with user details (id, username) and an expiration time of 1 hour.
  • Logging the Token: The generated JWT is printed to the console for use in authentication.

2. Code to verify a JSON web token

This code verifies a JWT using the jsonwebtoken library in Node.js. It checks if the token is valid and extracts the payload if authentication succeeds.

JavaScript
jwt.verify(token, 'abcde12345', (err, decoded) => {     if (err) {       console.log('Token is invalid');     } else {       console.log('Decoded Token:', decoded);     }   }); 

Output

Screenshot-2025-02-21-100424
Code to verify a JSON web token
  • Verifying the Token: The jwt.verify() method checks if the provided token is valid using the secret key.
  • Handling Errors: If verification fails, an error (err) occurs, and "Token is invalid" is logged.
  • Decoding Token Data: If valid, the decoded object contains the original user details.
  • Logging the Decoded Data: The decoded payload is printed to the console, showing user details from the token.

Common Issues During Development with JWT

JWT errors often arise from mismatched details or token problems:

  • JWT Rejected : This means the server couldn’t verify the token. It might happen because:
    • The JWT has expired: The token is no longer valid because it passed its expiration time.
    • The signature doesn’t match: The token might have been tampered with, or the signing keys have changed.
    • Other claims don’t match: For example, if the token was created for one app but sent to another, the app will reject it because it doesn't match the expected details.
  • JWT Token Doesn’t Support the Required Scope: A JWT contains permissions (called "scopes") that define what actions the user has agreed to. If the app requires more permissions than the token provides, it will be rejected. For instance, if the app needs permission to modify data, but the token only allows reading data, it won’t work.
  • JWT Decode Failed : This happens when the token isn’t in the expected format. For example, the client might expect the JWT to be base64 encoded, but if the server didn’t encode it that way, the client won’t be able to read it properly.

Advantages of using JSON Web Token

JWTs are widely used for authentication and authorization due to their numerous advantages:

  • Stateless Authentication: No need to store user sessions on the server; JWT contains all necessary data.
  • Compact & Fast: Being small in size, JWT is efficiently transmitted in HTTP headers, making it ideal for APIs.
  • Secure & Tamper-Proof: JWTs are signed using a secret key or public/private key pair, ensuring integrity.
  • Cross-Platform Support: Can be used with any technology (JavaScript, Python, Java, etc.) for authentication.
  • Built-in Expiry: Tokens can have an expiration time (expiresIn), reducing the risk of long-term access misuse.

Conclusion

JSON Web Tokens (JWT) provide a secure, fast, and stateless way to handle authentication. They are widely used in APIs, web apps, and mobile apps due to their compact size, cross-platform support, and built-in security features. By leveraging JWT, developers can ensure safe and efficient user authentication without storing sessions on the server.


Next Article
JSON Web Token (JWT)

A

aman neekhara
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Node.js
  • DSA
  • JSON
  • JavaScript-JSON

Similar Reads

    How to use JSON web tokens with Node.js ?
    JSON Web Token (JWT) is an Internet Standard that is used for exchanging data between two parties in a secure manner. It can't be easily hacked as it creates a digital signature with the secret key along with the HMAC algorithm).  JWT Structure: JSON Web Tokens consist of three parts separated by do
    4 min read
    How Long is a JWT Token Valid ?
    JSON Web Tokens (JWTs) are widely used for authentication and authorization in modern web applications and APIs. One crucial aspect of JWTs is their validity period, which determines how long a token remains valid after it has been issued. In this article, we'll delve into the factors influencing th
    6 min read
    JWT Authentication With Refresh Tokens
    Authentication is a critical part of web applications. Using JWT (JSON Web Tokens) for authentication is common, but adding refresh tokens provides an added layer of security and convenience. In this article, we’ll discuss how to implement JWT authentication with refresh tokens.JWT (JSON Web Token)J
    5 min read
    What is a Webhook and How to Use it?
    Webhooks allow interaction between web-based applications through the use of custom callbacks. The use of webhooks allows web applications to automatically communicate with other web-apps. Unlike traditional systems where one system (subject) keeps polling another system (observer) for some data, We
    6 min read
    How to Create and View Access Tokens in NPM ?
    Access tokens are important components in the npm ecosystem, used as authentication mechanisms for users to interact with npm registries securely. They grant permissions for actions such as publishing packages, accessing private packages, or managing user accounts. In this article, we will see how t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences