What is JWT (JSON Web Token)? How Does JWT Authentication Work?

Jump to

Imagine logging into your go-to app once and having immediate access to a set of services, never having to re-enter your login credentials. That convenient experience is enabled by a technology known as JWT, or JSON Web Token, that safely passes data from party to party in the form of a light, digitally signed token. 

JWTs have emerged as the foundation of contemporary web authentication, providing stateless, effective, and verifiable user sessions in a wide range of applications. JWT offers a compact, URL-safe way to represent claims to be exchanged between two parties, allowing secure information interchange and user authentication in distributed systems. But what is a JWT, and how does JWT authentication operate behind the scenes?

What is a JWT?

A JSON Web Token (JWT) is an open specification (RFC 7519) that describes a compact and self-contained JSON object for the secure exchange of information between parties. The information may be trusted and verified since it is signed digitally. JWTs may be signed with a secret (using the HMAC algorithm) or with a public/private key pair using RSA or ECDSA.

Structure of a JWT

A JWT is composed of three parts, each separated by a dot (.):


  1. Header: The header normally comprises two components: the token type (JWT) and the algorithm used in signing, e.g., HMAC SHA256 or RSA.
  2. Payload: Holds the claims, which are statements regarding an entity (usually, the user) and some other data. Claims may be registered, public, or private.
  3. Signature: Verifies that the token is not been tampered with. It is produced by applying the encoded header, encoded payload, secret key, and the algorithm present in the header.

What Is JWT Authorization?

JWT Authorization is a stateless authentication and authorization mechanism that does not require sessions and cookies. It is a secure way of transferring information because a JWT is signed digitally with a secret key that only the server knows. That means the information held in the JWT can’t be tampered with or changed while in transit. That’s how the common flow works:

  • Authentication: The credentials (e.g., username and password) of the user are sent to the server by the client for authentication.
  • Token Issuance: The server creates a JWT with user details and, if needed, authorization claims after successful authentication. The token is returned to the client.
  • Token Storage: The JWT is stored by the client, typically in local storage or cookies, to be used in future requests.
  • Token Transmission: In each request to a secured resource, the client passes the JWT in the HTTP Authorization header with the Bearer scheme.
  • Token Verification: The server accepts the request, identifies the JWT, and checks its signature with a secret key. If the token is legitimate, the server provides access to the requested resource. Otherwise, access is refused.


Key Points

  • JWTs are stateless, so the server does not have to hold session details for every user, which enhances scalability.
  • The JWT has a payload including user information and claims, a header for defining the signing algorithm, and a signature for integrity checking.
  • Everything in the JWT is exposed to anyone who possesses the token, so sensitive information should not be included within it.
  • JWTs are popular in web and mobile applications for secure and efficient authorization.


When to Use JWT Authentication?

JWT authentication is not a one-size-fits-all solution, but it’s ideal for situations where stateless, scalable, and cross-domain authorization is needed:

  • Stateless Authentication: JWTs are best when the server does not need to hold session data. Every request contains all of the data required for authorization, which makes the system scalable and appropriate for distributed systems.
  • Single Page Applications (SPAs): JWTs play nicely with SPAs since tokens can be stored client-side (e.g., in cookies or local storage) and sent with API requests, providing efficient session management without the need for server-side state.
  • Microservices: With microservices architectures, JWTs provide secure communication among services. A service can verify independently the token and user claims without a centralized session store, enabling decentralized authorization.
  • Cross-Domain Authentication and Single Sign-On (SSO): JWTs are particularly adapted to SSO solutions, in that they can be passed easily across different domains and systems, enabling users to sign in once and have access to several applications or services.

API Keys vs. JWT Authorization
API keys are straightforward, long-term identifiers most suitable for simple authentication and client identification, easy revocation, but with less inherent fine-grained control.

JWTs are packed, self-contained tokens that excel in stateless, scalable designs, with embedded access control information and short-lived credentials to enhance security, at the expense of increased setup complexity and reduced immediate revocability.

The table below summarizes these differences.

FeatureAPI KeysJWT Authorization
PurposeIdentifies the clientAuthenticates and authorizes the user
FormatLong string of charactersEncoded JSON object
SecurityLess secure, can be easily stolenMore secure, digitally signed, and encrypted
UsageSent as a parameter or headerSent as a bearer token in the authorization header
AuthenticationNot used for authenticationUsed for authentication
FlexibilityLimited flexibilityMore flexible, supports complex access control
Ease of UseSimple to useMore complex, requires token generation and verification
StandardizationNot standardizedStandardized, based on the JWT standard

While API Keys are simpler to use, they are less secure and less flexible than JWT authorization. JWT Authorization provides a more secure and flexible mechanism for authenticating and authorizing access to an API.

Steps To Implement JWT Authentication In Node.js


Implementing JWT Authorization in Your Application. Implementing JWT (JSON Web Token) authorization involves a series of clear steps to ensure secure, stateless authentication and access control:

Step 1: Initialize the node application using the following command.

Step 2: Installing required packages


Express: Web framework for Node.js.​ 

dotenv: Loads environment variables from a .env file.​ 

jsonwebtoken: Library to sign and verify JWTs

Step 3: Create Configuration File (.env).

Project Structure

Dependencies


Example: Below is the code example of the JWT Authentication with Node JS

To start the application, run the following command.

Output

POST Request

POST Response

GET Request:

GET Request Header:

GET Response:

How JWT Single Sign-On (SSO) Works for Multiple Web Apps

JWT-based Single Sign-On (SSO) allows users to log in once and easily access multiple web applications without having to re-log in to each application. Below is a comprehensive explanation of how it is done:

1. Centralized Authentication

  • The user is directed to a central authentication server (such as auth.example.com) when they attempt to access any participating application.
  • The user enters their credentials (username, password, etc.) on this central server.

2. Token Issuance

  • Upon successful authentication, the central server generates a JWT (JSON Web Token).
  • The JWT contains encoded user information and claims, such as user ID, roles, and token expiration time.
  • The token is cryptographically signed (using a secret or private key) to ensure its integrity and authenticity.

3. Token Sharing

  • The JWT is sent to the client, typically stored in a secure, HTTP-only cookie or passed via URL parameters or Authorization headers.
  • For SSO across multiple domains, the token can be shared using:
    • HTTP-only cookies with a domain scope that covers all participating apps (e.g., .example.com)
    • Secure transmission over HTTPS to prevent interception.
  • When the user navigates to another web app within the SSO ecosystem, the JWT is automatically sent along with the request, either via the cookie or explicitly in the Authorization header.

4. Token Validation

  • Each web application receives the JWT and verifies its signature using the shared secret or public key from the authentication server.
  • If the token is valid and not expired, the application extracts the user information from the token and grants access to protected resources.
  • If the token is invalid or expired, the user is redirected back to the authentication server for re-authentication.

Key Considerations

  • Statelessness: JWT SSO is stateless; session information is stored in the token itself, not on the server, making it scalable for distributed systems and microservices.
  • Security: Use short-lived tokens, secure cookies, HTTPS, and proper CORS (Cross-Origin Resource Sharing) configuration to prevent unauthorized access and token theft.
  • Token Refresh: Implement a refresh token mechanism to allow users to maintain sessions without frequent re-authentication.
  • User Experience: This setup provides a seamless user experience—users log in once and can access all authorized applications without repeated logins.

Example Flow

  1. User visits app1.example.com and is redirected to auth.example.com to log in.
  2. After a successful login, auth.example.com issues a JWT, which is stored in a secure cookie.
  3. User navigates to app2.example.com; the JWT is sent automatically.
  4. app2.example.com verifies the JWT and grants access without prompting for login again.

This approach streamlines the user experience and enhances security across multiple applications.

Wrap up

JSON Web Tokens (JWTs) provide a secure and efficient means of authentication and authorization in contemporary web applications. A grasp of JWT structure, advantages, and application will allow developers to improve the security and scalability of their applications. Building a single-page application, a microservices system, or deploying Single Sign-On, JWT presents a flexible and secure mechanism for handling user authentication and access control.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may also like

Boost C++ Libraries logo and code snippets illustrating integration

Introduction to the Boost C++ Libraries

What if your C++ code were quicker to write, more secure to execute, and simpler to upkeep, without having to reinvent the wheel? That’s precisely what the Boost C++ Libraries

Agile team discussing user story mapping and story point estimation

Your Guide to Story Points & Estimation

Story points are a significant aspect of user story mapping, and most agile teams use them when planning. However, they are not as easy as assigning numbers to tasks or

Categories
Scroll to Top