SoFunction
Updated on 2025-04-08

Implementation method of generating tokens in Express

Express is a very popular web framework in , providing flexible and powerful tools to create web applications. Security is a crucial consideration in many application scenarios, especially in user authentication. Generating and using Tokens is a common user authentication method that can effectively ensure communication security. This article will introduce in detail how to generate tokens in Express and combine them with common libraries (such asjsonwebtoken) usage helps you build safe applications.

1. Basic concepts of token certification

1. What is a token?

Token is a credential used for authentication. Unlike the traditional session-based authentication mechanism, Tokens are a stateless authentication method that is usually generated by the server and sent to the client. In subsequent requests, the client will send the token back to the server, and the server confirms the user's identity by verifying the validity of the token.

2. Why choose Token authentication?

  • Statelessness: Unlike session-based authentication, tokens are stateless and do not need to save user status information on the server side, greatly simplifying the server's processing.
  • flexibility:Tokens can be used for cross-domain authentication, especially in API design. Tokens are a very common authentication method in RESTful interfaces.
  • Security: Through encryption and signature technology, the content of Tokens is safe and timely, reducing the risk of Tokens being stolen.

2. Commonly used Token types

1. JWT(JSON Web Token)

JWT is a very popular Token format. It uses JSON as the payload and ensures the integrity of data through signature. JWT consists of three parts: Header, Payload and Signature.

  • Header: Describe metadata of the token, such as the signature algorithm used (such as HMAC, SHA256, etc.).
  • Payload: Contains user information and custom claims, such as user ID, role, etc.
  • Signature: Encrypt the generated signatures of the Header and Payload through the specified signature algorithm to verify the integrity of the token.

2. Bearer Token

Bearer Token is an HTTP-based authentication method, and the client passes it in the request.AuthorizationThe head carries the token, and the server parses the token and confirms its validity. This method is usually used with JWT.

3. Basic steps to generate a token in Express

1. Install the jsonwebtoken library

First, we need to usejsonwebtokenLibrary to generate and verify tokens. This library can be installed through npm:

npm install jsonwebtoken

2. Code examples for generating tokens

In Express, we can generate a JWT with the following code:

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

// Secret key, used to sign Tokenconst SECRET_KEY = 'your-secret-key';

// Simulate the login interface and generate the token('/login', (req, res) => {
  // Simulate to obtain user information from the database  const user = { id: 1, username: 'user1', role: 'admin' };

  // Generate a token, set the expiration time to 1 hour  const token = ({ id: , role:  }, SECRET_KEY, { expiresIn: '1h' });

  // Return the token to the client  ({ token });
});

// Listen to the port(3000, () => {
  ('Server is running on port 3000');
});

In the above code, we created a/loginInterface. When the user requests this interface, the server generates a JWT and returns it to the client.Methods are used to generate tokens,SECRET_KEYIt is the key used when signing.expiresInThe parameters are used to set the validity period of the token.

3. Code example for verifying the token

In the user's subsequent request, the client needs to send the token to the server, and the server needs to verify the validity of the token. It can be implemented through the following code:

// Middleware for verifying the tokenfunction authenticateToken(req, res, next) {
  const authHeader = ['authorization'];
  const token = authHeader && (' ')[1];

  if (!token) {
    return (401); // If there is no Token, return 401 Unauthorized  }

  // Verify Token  (token, SECRET_KEY, (err, user) => {
    if (err) {
      return (403); // If the Token is invalid, return 403 prohibited access    }

    // Save the decrypted user information to the request object     = user;
    next();
  });
}

// Protected routes, only valid tokens can access('/protected', authenticateToken, (req, res) => {
  ({ message: 'This is a protected route', user:  });
});

In the above code, we define aauthenticateTokenMiddleware, it parses the token from the request header and usesMethod Verification Token. If the verification is passed, the user information will be attached to the request object, allowing subsequent processing.

4. Token validity period and refresh mechanism

1. Set the validity period of the token

In production environments, tokens usually set a short expiration period (such as minutes to hours). We can passThe method ofexpiresInParameters to set the validity period.

const token = ({ id:  }, SECRET_KEY, { expiresIn: '15m' }); // Token is valid for 15 minutes

2. Refresh Token

When the token is about to expire, the client can request the server to refresh the token. Usually, refreshing the token requires the user to provide the old token, and the server verifies the validity of the old token and generates a new token. Here is a simple example of refreshing a token:

('/refresh', authenticateToken, (req, res) => {
  const user = ; // Get user information from old tokens  const newToken = ({ id: , role:  }, SECRET_KEY, { expiresIn: '1h' });
  ({ token: newToken });
});

5. Things to note when using Token

1. Secure storage of tokens

The client needs to properly store the tokens to avoid the token being leaked. Common storage locations include:

  • The browser's localStorage: Convenient to persistent storage, but vulnerable to XSS attacks.
  • Browser cookies: Can be setHttpOnlyAttributes to enhance security, but need to be protected against CSRF attacks.

2. Use HTTPS

When transmitting a token, HTTPS should always be used to ensure that the token will not be stolen.

3. Token revocation mechanism

JWT itself is stateless and cannot be revoked once generated. Therefore, if a token needs to be invalid immediately, you can record the revoked token on the server side through the blacklist mechanism and check whether the token is in the blacklist every time you request it.

6. Summary

The Token authentication mechanism is an efficient and flexible authentication method, especially suitable for distributed systems and stateless APIs. By Express andjsonwebtokenLibrary, we can easily implement a Token-based authentication system and ensure the security of communication. In actual applications, we should reasonably set the validity period, storage method and security mechanism of the token according to business needs to ensure the security of the system and user experience.

This is the article about the implementation method of Express generation token generation. For more related Express generation token content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!