What is JSON Web Token

JSON Web Token (JWT), also known as JSONtoken, is an open standard (RFC 7519) for securely transmitting information between web applications. It uses a compact, self-contained way to represent information, often used for authentication and authorization. The design goal of JWT is to ensure the integrity and security of information while being easy to use and transmit.

Structure of JWT

JWT consists of three parts, .separated by:

  1. Header : Contains metadata and description about the token, usually including the token type ( typ) and signature algorithm ( alg) and other information. This part is an JSONobject and is usually base64urlencoded.

  2. Payload : Contains the data that needs to be transmitted. It is also an JSONobject and usually includes some declarations ( claim) and user-defined data. Common statements include:

    • iss(Issuer): The issuer of the token.
    • sub(Subject): The subject of the token, usually the user's unique identifier.
    • aud(Audience): The token's audience, indicating which recipients the token is intended for.
    • exp(Expiration Time): The expiration time of the token.
    • iat(Issued At): The issuing time of the token.
    • nbf(Not Before): The validity time of the token.
    • jti(JWT ID): The unique identifier of the token.

    In addition to standard declarations, you can also add custom data in the payload.

  3. Signature : Used to verify the authenticity and integrity of the JWT. The signature is usually generated by combining the header and payload parts, using a secret key to perform a hash operation, and then comparing it with the signature part in the token. This part ensures that the token has not been tampered with during transmission.

Here is an example of a JWT:

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

Payload:
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature:
HMACSHA256(
  base64UrlEncode(Header) + "." +
  base64UrlEncode(Payload),
  secret_key
)

In the above example, the Header specifies the use of the HS256 (HMAC SHA-256) algorithm for signing. The Payload contains information such as the subject (sub), name (name), and issuance time (iat). The Signature uses a secret key (secret_key) to generate.

JWT workflow

The JWT workflow usually involves three main roles: Issuer, User, and Verifier.

  1. Issuer : The issuer is the entity responsible for creating the JWT. The issuer processes the user's information with some claims and a signature, generates a JWT, and sends it to the user.

  2. User : The user is the holder of JWT, usually an entity that needs to transfer information between different applications. Users can send JWT to different applications for authentication or authorization when needed.

  3. Verifier : The verifier is the entity responsible for validating the JWT. After receiving the JWT, they will first parse the JWT Header and Payload, and then use the pre-shared key to verify the validity of the Signature. If the verification is successful, the verifier can trust the information contained in the JWT.

The workflow of JWT is as follows:

  • The user requests a token from the issuer through some means (such as username and password login).
  • After the issuer verifies the user's identity, it creates a JWT containing the user's information and some claims, and then uses its own private key to sign the JWT.
  • The issuer sends the JWT to the user.
  • When users communicate with different applications, they can send JWT to the application as authentication or authorization credentials.
  • After the application receives the JWT, it uses the public key previously shared with the issuer to verify the JWT's signature to ensure that the JWT has not been tampered with.
  • If the JWT verification passes, the application can trust the information and perform appropriate operations as needed.

Advantages of JWT

JWT is widely used in modern applications because it has several advantages:

  1. Lightweight and self-contained : JWT is a compact text format that is easy to transmit and parse. All necessary information is contained in the JWT itself, no session state needs to be maintained on the server.

  2. Distributed Authentication : JWT makes authentication in distributed systems simpler because different applications can share the same JWT issuer without needing to store user credentials in their own databases.

  3. Stateless : Since the JWT itself contains all necessary information, the server does not need to maintain session state, which is helpful for load balancing and fault tolerance.

  4. Extensibility : JWT payload can contain custom claims and additional information can be added according to the needs of the application.

  5. Security : JWT uses signatures to protect its integrity and prevent tampering. JWT security can be ensured using appropriate algorithms and keys.

scenes to be used

JWT is usually used in the following scenarios:

  1. Authentication : After the user logs in, the issuer can generate a JWT containing the user's information, and the user can carry the JWT in the request to prove their identity.

  2. Authorization : Applications can use JWTs to authorize users to access certain resources or perform specific actions. The Payload of JWT can be packaged

Contains user role and permission information.

  1. Single sign-on (SSO) : JWT can be used to implement single sign-on. Users only need to log in once to access multiple associated applications.

  2. Password reset : JWT can be used to generate a token containing password reset information, which the user can use to reset their password.

  3. Information exchange : JWT can be used to securely exchange information between different applications, such as in a microservices architecture.

security considerations

While JWT is useful in many scenarios, it also needs to be used with caution to ensure security:

  1. Key management : Secure management of keys is key. Leaking keys can lead to token forgery, so proper key management measures such as regular key rotation are required.

  2. Expiration time : JWT usually contains an expiration time (exp) statement. Applications need to regularly check the validity of the token and ensure that expired tokens are not used.

  3. Asymmetric encryption : For highly sensitive information, consider using asymmetric encryption algorithms to increase security. In this case, the verifier uses the issuer's public key to verify the signature.

  4. Avoid storing sensitive information in the token : Try to avoid storing sensitive information in the payload of the JWT, because the payload part is Base64 encoded and may be decoded.

  5. Use HTTPS : JWTs can be intercepted during transmission, so it is recommended to always use HTTPS when using JWTs to ensure the security of the communication.

Sample app: Validating JWT using Node.js and Express

Here is a simple example validating a JWT using Node.js and Express:

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

const app = express();
const secretKey = 'your-secret-key';

// 中间件:验证JWT
const verifyToken = (req, res, next) => {
    
    
  const token = req.headers.authorization;
  
  if (!token) {
    
    
    return res.status(401).json({
    
     message: '无法验证身份' });
  }

  jwt.verify(token, secretKey, (err, decoded) => {
    
    
    if (err) {
    
    
      return res.status(401).json({
    
     message: '身份验证失败' });
    }
    req.user = decoded;
    next();
  });
};

// 路由:受保护的资源
app.get('/protected', verifyToken, (req, res) => {
    
    
  res.json({
    
     message: '欢迎访问受保护的资源', user: req.user });
});

// 路由:生成JWT
app.post('/login', (req, res) => {
    
    
  const user = {
    
     id: 1, username: 'user123' };
  const token = jwt.sign(user, secretKey, {
    
     expiresIn: '1h' });
  res.json({
    
     token });
});

app.listen(3000, () => {
    
    
  console.log('服务器运行在端口 3000');
});

In the above example, the server was created using the Express framework and contains two routes. /loginRoutes are used to generate JWTs. /protectedRoutes are protected and can only be accessed by requests carrying valid JWTs.

in conclusion

JSON Web Token (JWT) is a standard widely used for authentication and authorization. It has the advantages of being lightweight, self-contained, distributed, stateless, and scalable, and is suitable for a variety of application scenarios. However, when using JWT, you need to pay attention to key management, security and appropriate expiration time to ensure the security of the application.

JWT plays an important role in modern applications, providing developers with a flexible and secure way to transmit information and authenticate users. It has become one of the standard authentication methods for many web applications, mobile applications and APIs, helping developers build more secure and flexible applications.

Guess you like

Origin blog.csdn.net/i042416/article/details/132972917