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?
- User Logs In: The client (browser) sends login credentials to the server.
- Server Generates JWT: If credentials are valid, the server creates a JWT containing user data and signs it with a secret key.
- Token Sent to Client: The JWT is sent back to the client and stored (usually in localStorage or a cookie).
- Client Sends Token in Requests: For protected routes, the client includes the JWT in the Authorization header (Bearer Token).
- 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 JWTA JWT consists of three parts, separated by dots (.)
Header. Payload. Signature
- Header: Contains metadata about the token, such as the algorithm used for signing.
- Payload: Stores the claims, i.e., data being transmitted.
- Signature: Ensures the token's integrity and authenticity.
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
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
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.
Similar Reads
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.Basics of Web Development To better understand t
7 min read
HTML Tutorial
CSS Tutorial CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and enhance website presentation. CSS is one of the three main components of a webpage, along with HTML and JavaScript.HTML adds Structure to a web page.JavaScript adds logic to it and CSS makes it visually appealing or
7 min read
JS Tutorial
JavaScript TutorialJavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
8 min read
JSON TutorialJSON (JavaScript Object Notation) is a widely-used, lightweight data format for representing structured data. Used Extensively : Used in APIs, configuration files, and data exchange between servers and clients.Text-based: JSON is a simple text format, making it lightweight and easy to transmit.Human
5 min read
TypeScript TutorialTypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Vue.js TutorialVue.js is a progressive JavaScript framework for building user interfaces. It stands out for its simplicity, seamless integration with other libraries, and reactive data binding.Built on JavaScript for flexible and component-based development.Supports declarative rendering, reactivity, and two-way d
4 min read
jQuery TutorialjQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Front End
React TutorialReact is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
Angular TutorialAngular is a powerful, open-source web application framework for building dynamic and scalable single-page applications (SPAs). Developed by Google, Angular provides a comprehensive solution for front-end development with tools for routing, form handling, HTTP services, and more.Designed for buildin
4 min read
Backend
Node.js TutorialNode.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Express.js TutorialExpress.js is a minimal and flexible Node.js web application framework that provides a list of features for building web and mobile applications easily. It simplifies the development of server-side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.Built on Node.
4 min read
PHP TutorialPHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
8 min read
Laravel TutorialLaravel is an open-source PHP web application framework that has gained immense popularity since its inception in 2011, created by Taylor Otwell. This renowned framework empowers developers to build robust, scalable web applications with remarkable ease. As a developer-friendly framework, Laravel of
3 min read
Database
Web Technologies Questions The following Web Technologies Questions section contains a wide collection of web-based questions. These questions are categorized based on the topics HTML, CSS, JavaScript, and many more. Each section contains a bulk of questions with multiple solutions. Table of Content HTML QuestionsCSS Question
15+ min read