logo
TrungTQ

Using JWT for Authentication: Best Practices and Common Mistakes

  • Author: Administrator
  • Published On: 08 Jun 2025

Using JWT for Authentication: Best Practices and Common Mistakes

Welcome to our in-depth guide to using JSON Web Tokens (JWT) for authentication. This article aims to provide a comprehensive look at JWT, from the basics to best practices and common mistakes.

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, token-independent method for transmitting information between parties as a digitally signed JSON object. JWT is commonly used for authentication and authorization.

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

  1. Header: Specifies the token type and encryption algorithm. For example: {"alg": "HS256", "typ": "JWT"}
  2. Payload (Data): Contains claims – information about the user or entity the token represents. For example: {"sub": "1234567890", "name": "John Doe", "admin": true}
  3. Signature: Created by encrypting the header, payload, and a secret key using the algorithm specified in the header. This signature ensures that the token has not been tampered with.

Example of a complete JWT:

 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

How JWT Works

The process of using JWT usually goes like this:

  1. Authentication: The user provides login credentials (e.g. username and password).
  2. Token issuance: If the credentials are valid, the server generates a JWT containing information about the user and returns it to the user.
  3. Token storage: The user stores the JWT (usually in localStorage or a cookie).
  4. Resource access: When a user wants to access a protected resource, they send the JWT along with the request (usually in the Authorization header).
  5. Token authentication: The server authenticates the JWT by checking the signature and ensuring that the token has not expired.
  6. Grant access: If the JWT is valid, the server grants access to the resource.

Best Practices When Using JWT

  1. Use HTTPS: Always use HTTPS to protect JWTs from being stolen during transmission.
  2. Use Strong Secret Keys: Use a strong secret key and keep it secret. Avoid using easily guessable secret keys or storing them in code.
  3. Set Expiration Time: Set a short expiration time for the JWT to minimize the risk if the token is stolen. Use claim exp to specify the expiration time.
  4. Using Refresh Token: Use refresh token to reissue new JWT when old JWT expires. Refresh token usually has longer lifetime and is stored more securely.
  5. Do Not Store Sensitive Information in the Payload: Avoid storing sensitive information such as passwords or financial information in the JWT payload, as the payload can be easily decoded.
  6. Using JTI (JWT ID): Use jti claims to create a unique identifier for each JWT. This allows you to track and revoke specific JWTs if needed.
  7. Server-side JWT Authentication: Always validate JWT on the server before granting access to resources. Do not rely on client-side JWT authentication.
  8. Use Secure Encryption Algorithms: Prefer to use strong encryption algorithms like RS256 or ES256 instead of HS256, as they use public and private keys, enhancing security.

Common Mistakes When Using JWT

  1. Storing Secret Key In Code: This is a very serious mistake. Secret key should be stored in an environment variable or secret management system.
  2. No Expiration Check: Skipping the JWT expiration check can lead to attackers using expired tokens to gain unauthorized access.
  3. Using Algorithm alg: none: The none algorithm allows JWT creation without a signature, which is dangerous because anyone can create a valid JWT.
  4. No JWT Validation on Server: Relying on client-side JWT validation is insecure, as the client can be controlled by an attacker.
  5. Storing Sensitive Information in Payload: Storing sensitive information in payload can lead to data leakage if JWT is stolen.
  6. Don't Use Refresh Token: Not using refresh tokens can degrade user experience, as they have to log in again more often.
  7. Not Revoking JWT When Necessary: Not having a mechanism to revoke JWTs (e.g. when a user logs out or changes their password) can lead to JWTs being abused for unauthorized access.

Illustrative Example

Here is a simple example of how to create and validate a JWT using the jsonwebtoken library in Node.js:

 const jwt = require('jsonwebtoken'); // Tạo JWT const payload = { userId: '123', username: 'johndoe' }; const secretKey = 'your-secret-key'; const options = { expiresIn: '1h' }; const token = jwt.sign(payload, secretKey, options); console.log('JWT:', token); // Xác thực JWT jwt.verify(token, secretKey, (err, decoded) => { if (err) { console.error('Lỗi xác thực JWT:', err.message); } else { console.log('JWT hợp lệ. Thông tin giải mã:', decoded); } });

Conclude

JWT is a powerful tool for authentication and authorization, but it needs to be used properly to ensure security. By following best practices and avoiding common mistakes, you can get the most out of JWT without worrying about security issues.

Hopefully this guide has given you a good overview and details on how to use JWT. Good luck implementing JWT in your projects!

  • Share On: