From the NodeJS course at Coderwhy

Check out the JWT mechanism jwt.io/

Know the token

Cookies and sessions have a number of drawbacks:

  • Cookies are attached to every HTTP request, so they increase traffic (some requests are actually not needed);

  • Cookies are passed in plaintext, so there are security issues;

  • The Cookie size limit is 4KB, which is not enough for complex requirements;

  • For clients outside the browser (such as iOS and Android), you must manually set cookies and sessions.

  • How can distributed systems and server clusters ensure that other systems parse sessions correctly?

Therefore, in the current development process of front end separation, the use of token for authentication is the most common situation:

  • Token can be translated as token;

  • That is, after verifying that the user account and password are correct, issue a token to the user; This token serves as a credential for subsequent users to access some interface or resource;

  • We can judge whether the user has permission to access according to this certificate;

Therefore, the use of token should be divided into two important steps:

  • Token generation: A token is issued during login.

  • Verify token: Verifies the token when accessing certain resources or interfaces.

Tokens are implemented through JWT

The Token generated by JWT consists of three parts:

  • header

    • Alg: indicates the encryption algorithm used. The default encryption algorithm is HMAC SHA256 (HS256), which uses the same key for encryption and decryption.
    • Typ: JWT, fixed value, usually written as JWT; It is encoded using the base64Url algorithm
  • payload

    • You can put the user’s ID and name in the payload;
    • Iat (issued at);
    • We can also set expiration time: exp (expiration time);
    • It is encoded using the base64Url algorithm
  • signature

    • Set up a secretKey by merging the results of the first two for HMACSHA256(default encoding) algorithm;

    • HMACSHA256(base64Url(header)+.+base64Url(payload), secretKey);

    • If the secretKey is exposed, it is a very dangerous thing, because then the token can be simulated and decrypted;

Note: The first two fields are base64 encoded and can be decoded backwards. But the last field usually doesn’t work.

Encryption mode of token generation

Symmetric encryption

The token is encrypted and decrypted using the same secret key. HS256 encryption algorithm

Asymmetric encryption

We use two secret keys for token encryption and decryption

  • Private key: used to issue tokens;
  • Public key: used to verify the token;

How do you generate public and private keys?

  • The MAC directly runs the following command on the terminal.
  • On a Windows PC, you need to run the following command in git bash.
    openssl
    genrsa -out private.key 1024
    rsa -in private.key -pubout -out public.key
Copy the code

Use tokens in development

In real development, we can do this directly with a library: JsonWebToken;


    const jwt = require("jsonwebtoken");
    async login (ctx, next) {
        // Retrieve user after login successfully
        const { id, username } = ctx.user;
        // Generate a token. Generate tokens using private keys
        const token = jwt.sign({ id, username }, PRIVATE_KEY, {
          // Set the expiration time
          expiresIn: 60 * 60 * 24.// Set the encoding format
          algorithm: 'RS256'
        })
        ctx.body = {
          id,
          username,
          token
        }
      }
Copy the code

Parsing the token

// Verify authorization, decrypt
    async function verifyAuth (ctx, next) {
      const authorization = ctx.request.headers.authorization;
      const token = authorization && authorization.replace("Bearer "."");
        // Resolve the token through the public key
        const user = jwt.verify(token, PUBLIC_KEY, {
          algorithms: ["RS256"]})// Save user data for later use
        ctx.user = user
        await next()
    }
Copy the code