Did you know? All Video & Audio API plans include a $100 free usage credit each month so you can build and test risk-free. View Plans ->

JSON Web Token

When building applications, you must verify user identity and prevent unauthorized access to sensitive data. JSON Web Tokens are popular for managing user authentication and authorization because they're fast, stateless, and scalable.

What Is a JSON Web Token?

JSON Web Tokens (JWTs) are stateless credentials that transmit information securely between parties in JSON format. They embed authentication and authorization information within the token, eliminating the need for server-side session storage. Each token is signed cryptographically, making sure the JSON content remains tamper-proof.

JWTs provide seamless user authentication and identity verification for secure client-server communications.

For example, JWTs are commonly used in multiplayer gaming apps to verify player identities, securing logins and interactions between players and servers.

How Do JWTs Work?

JWTs encode user information into a token with three components:

  • Header
  • Payload
  • Signature

The header is a JSON object that specifies the token type and signing algorithm. A hypothetical JWT header could look like this:

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

This indicates the token uses the HS256 signing algorithm, while typ is the token type, which is usually JWT.

The payload contains claims, which represent information about the user. Some of the claims include:

  • iss: the JWT issuer
  • sub: the subject user of the token
  • aud: the audience of the token (the application the JWT is intended for)
  • exp: the token's expiry
  • iat: the timestamp when the token was created

An example payload looks like:

{
  "sub": "9876543210",
  "name": "Dennis Joe",
  "iat": 11252072011
}

Both the header and the payload are encoded into base64 URL-safe strings and concatenated with a period, with the resulting string used for the signature. This creates a concatenated string like:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5ODc2NTQzMjEwIiwibmFtZSI6IkRlbm5pcyBKb2UiLCJpYXQiOjExMjUyMDcyMDExfQ

The signature is created by hashing the encoding header and payload with a secret key using the specified algorithm.

Here is an example of how to create a JWT signature using the HS256 algorithm:

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

This generates a JWT string that looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5ODc2NTQzMjEwIiwibmFtZSI6IkRlbm5pcyBKb2UiLCJpYXQiOjExMjUyMDcyMDExfQ.0Kx2CZh3Msx2_HB2-sswvK0CNcwZ2H0ZuUnkpFX74U0

You can use this token in API requests, where the server uses the same secret to verify its integrity.

How to Use JWT for Authentication

One possible way to implement JWT to secure your application involves the following steps:

Step 1: Setup

When building an application, you need to first install a JWT library. For example, you can use jsonwebtoken for Node.js or pyjwt for Python. Then, you should configure the signing algorithm with your secret key.

Secondly, set up your sign-in endpoints to validate user credentials and issue a JWT.

Step 2: JWT Issuance

After validating user credentials, you should construct the payload with the user claims (such as user ID, email, and permissions) and sign it with the secret key. Also, consider issuing a refresh token for a longer lifespan and send both to the client.

const jwt = require('jsonwebtoken');
const payload = { sub: user.id, email: user.email };
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '15m' });
const refreshToken = jwt.sign({ sub: user.id }, process.env.REFRESH_SECRET, { expiresIn: '7d' });

In the above setup, the secret and refresh tokens are securely stored in environment variables.

Step 3: Client Token Storage

Make sure that you securely store the JWTs on the client side, preferably using HttpOnly cookies to avoid cross-site scripting (XSS) attacks.

res.cookie('jwt', token, { httpOnly: true, secure: true });

For mobile apps, store tokens securely in the system-provided secure storage: SharedPreferences for Android or Keychain for iOS.

Step 4: Request Authentication

Whenever you send requests to protected routes, the client attaches the JWT in the authorization header:

Authorization: Bearer <JWT_TOKEN>

Step 5: Server Verification and Authorization

Upon receiving the request, the server verifies the JWT signature to make sure it's valid and not expired. It also checks claims to determine whether the user has the right permissions.

Step 6: Token Refresh

Since your access tokens expire quickly, you should implement a refresh token to renew expired access tokens without requiring users to re-authenticate. The refresh token is crucial for applications where the user needs to stay logged in, like online gaming or live streaming apps.

Step 7: Logout and Token Revocation

The token should clear upon the user's logout:

res.clearCookie('jwt');

However, you can consider implementing revocation strategies, enabling the application to invalidate JWTs upon logout or when a password changes.

Benefits of JWTs

JWTs provide numerous advantages that make them an ideal choice for authentication, including:

  • Statelessness and scalability: JWTs are stateless, meaning they're self-contained and don't need server-side session storage. All necessary information is embedded within the token, making JWTs ideal for microservices and distributed systems. For example, large-scale applications, like real-time collaboration apps, can use JWTs to reduce the complexity of managing session data across multiple servers, which improves scalability.
  • Compactness and efficiency: JWTs use base64 encoding. This creates compact tokens that are easy to transmit via HTTP headers or URLs. It also minimizes network overhead and benefits high-traffic applications such as social apps, where low latency is essential.
  • Cross-domain/SSO friendliness: JWTs enable single sign-on (SSO) for cross-domain authentication, allowing different parts of an application to share user data securely while running on separate domains. In this implementation, a single token can authenticate multiple services or domains, simplifying cross-origin communication. This feature is ideal for systems that require multiple service integrations, such as telehealth services.
  • Robust security: The use of signing algorithms makes JWTs tamper-proof during transit. Also, they can be encrypted with JSON Web Encryption (JWE) to protect sensitive data. This makes sure that only the intended recipient can read the token's data.
  • Mobile-friendliness: Due to their stateless nature and compact design, JWTs are an ideal choice for mobile apps. Additionally, tokens can be made safer with secure storage mechanisms (like SharedPreferences and Keychain), avoiding the complexities of managing cookies.
  • High performance: JWTs are verified using the same signature. This means there's no need for database lookups for session validation. The server can handle more requests without querying session data, which improves application performance.
  • Flexible authentication: Developers can use custom claims to include additional data in the token, such as user roles and permissions. This streamlines authorization workflows by directly enabling more fine-grained access control from the token.

Best Practices for Using JWTs

To strengthen the security of your JWT-based authentication system, follow these practices:

Use strong cryptographic algorithms.

It's recommended to use secure, robust algorithms such as HS256 or RS256 when generating JWTs. These algorithms are strong and difficult to break, enhancing token security.

You should also use a strong, complex secret key that hackers cannot guess and store it as an environment variable instead of hardcoding it in your codebase.

Handle token revocation and short expiration times.

Set short expiration times for access tokens, such as 15 minutes. This limits the security impact when a token is stolen. You should combine the short expiration times with long-lived refresh tokens that allow new access token renewal.

Don't put sensitive data in JWTs.

Avoid placing sensitive data such as passwords and personally identifiable information (PII) in JWTs, as they are not encrypted by default and hackers can decode them. If storing sensitive data is necessary, consider encrypting the payload.

Validate tokens properly.

Always validate JWTs on the server side. Also, verify the token's signature, including all claims. This prevents token misuse.

Store tokens securely.

You should avoid storing tokens in session or local storage as they are vulnerable to XSS attacks. Instead, store them in HttpOnly cookies and Secure flags. Storing them in HttpOnly means that JavaScript running in the browser cannot access the tokens, securing them from attackers.

Frequently Asked Questions

What Is the Purpose of JWT Claims?

Claims, also known as assertions, are information about the user and the context of the tokens, such as user ID, expiration times, roles, and timestamps. They represent the identity and authorization details, allowing servers to determine the user’s permissions without additional queries.

What Is the Role of JSON Web Tokens?

JWTs provide a secure and convenient user authentication method in web and mobile apps. They securely transmit information between parties in JSON format to authorize resource access.

How Do You Decode a JWT Token Online?

Decoding a JWT is the process of revealing the header and payload in a readable JSON format.

To decode a JWT, you can use tools to convert encoded data into readable JSON, like jwt.io. However, these tools do not verify the signatures, so you should always validate the token server-side to be sure of its authenticity.

What Is the Difference Between JWT and OAuth?

JWT is a standard for sharing information between a client and a server in JSON format. It contains claims about the user or client and is used for authentication and authorization in applications. In contrast, OAuth is an authorization framework that issues access tokens to grant limited access to resources without exposing login credentials.