This is the 11th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

1. Login registration process

To achieve user login registration, there are mainly two schemes cookie-session mode and JWT mode

The implementation scheme uses cookie-session mode

1. The requester sends the account password to the server to verify the account availability. 2. If the authentication succeeds, a session is generated and saved on the server. 3. The server returns a session ID and saves it in the cookie of the client. 4. The client carries cookies when requesting. 5. The server parses the session ID carried in the cookie and returns the response data after the authentication passes.

JWT mode

1. A user registers in the system and enters the user name, password and other information, which is saved in the user table. 2. When a user logs in to the system, he or she enters the user name, password and other information. The backend verifies that the information is correct and gives the front-end a special identifier token 3. For the interface to be verified later, the front-end directly adds the identifier token to the back-end for identity parsing and subsequent processing

2. Egg back-end login to register cookies,seesion scheme

The relationship between cookies and sessions

Cookie is an encrypted string maintained by the browser. Session is a key-value pair maintained by the back end. The key is the cookie of the front end. The cookie from the front end is passed to the back end, and the back end traverses the session key-value pair maintained by the cookie as the key to find the specified value, which is used to distinguish the user’s identity.

How to write cookies

When the browser requests the server, for example, localhost:3000, server 123.12.12.89:7001. Browser domain name localhost: 3000 request server 123.12.12.89:7001 / setcookie an interface, the specified in the cookies, egg. Used in js CTX. Cookies, set (key, value), Application cookie: 123.12.12.89 (localhost:3000) : 123.12.12.89 (localhost:3000) That’s the theory, but what you see is that it doesn’t write to the browser, and here’s why

Cookie session supports same-domain (same-level domain name is ok, and the second-level domain name and port can be different)

In this case, local debugging requires front-end host configuration

Font.morant.com front-end IP end.morant.com back-end IP copy codeCopy the code

If host is configured, each request will use a domain name, but will be mapped to a different IP address, so the purpose of the domain is achieved. At this point, you can see that font.morant.com is written to the cookie. There may be cross-domain in the middle. This method is more and easier to solve.

Automatic cookie carrying

So if your interface is a GET request, and the browser requests it, then you’ll find that it can be carried automatically, but if ajax requests it will have problems

Ajax carry cookies

Front-end axios set axios. Defaults. WithCredentials = true;

The back-end set

Config. cors = {origin: 'front-end specified source + port ', allowMethods: 'GET, HEAD, PUT, POST, DELETE, PATCH, OPTIONS', / / the following article and can be Shared across domains session, front-end ajax requests at the same time also with the response parameters of credentials: true,}; Copy the codeCopy the code

At this point you notice that the second refresh of the written cookie is automatically carried on the request head

3. Egg login to register the JWT scheme

JSON Web Token(JWT) is currently the most popular cross-domain authentication solution. It is an authentication and authorization mechanism. JWT is a JSON-based open token () implemented to pass declarations between network application environments. JWT declarations are typically used to pass authenticated user identity information between the identity provider and the service provider in order to retrieve resources from the resource server. For example, for user login.

It is appropriate to use the scenario processing specifically addressed to middleware in the previous section, where all requests are previously authenticated by the middleware.

1. Installegg-jwt, the user issues and decrypts the token
npm i egg-jwt --save
Copy the code
In 2.plugin.jsConfigure the plug-in and enable it
// Configure single sign-on
exports.jwt = {
  enable: true.package: 'egg-jwt'};Copy the code
3. First manually set an encrypted salt scret onconfig.default.jsEasy to modify access unified configuration
  config.jwt = {
    secret: "123456",
  };
Copy the code
4. Get the username and password in the database to check whether it is correct. The password may be encrypted and decrypted and put into the database
5. Issue token (willconfig.default.jsSecret is taken out for encryption, and data is used to encrypt database identifiers such as userId.
 const token=this.app.jwt.sign(data, this.app.config.jwt.secret, { expiresIn: 30 * 24 * 60 * 60 + 's' }
Copy the code
6. Store the token as the return value of the request to the front-end
7. Truly validate middleware logic
'use strict';

// middleware/jwtErr.js
module.exports = options= > {
  return async function jwtErr(ctx, next) {
    let token = ' ';
    if (
      ctx.headers.authorization && ctx.headers.authorization.split(' ') [0= = ='Bearer'
    ) {
      token = ctx.headers.authorization.split(' ') [1];
    } else if (ctx.query.accesstoken) {
      token = ctx.query.accesstoken;
    } else if (ctx.request.body.accesstoken) {
      token = ctx.request.body.accesstoken;
    }
    let decode = ' ';
    if (token) {
      try {
        / / decoding token
        decode = ctx.checkToken(token, options.secret);

        // Determine whether to decode
        if(! decode) { ctx.returnBody(false, {}, 'Token is invalid, please log in again '.401);
          return;
        }

        if (decode && decode.exp <= new Date(a) /1000) {
          ctx.responseData({}, 'Token has expired, please log in again '.401.401);
        }
        // The decoded data is bound to the request
        ctx.request.decode = decode;
        await next();
      } catch (error) {
        ctx.responseData({}, 'Token invalid, please re-upload'.401.401);
        return; }}else {
      ctx.responseData({}, 'No token, please upload token'.401.401);
      return; }}; };Copy the code
8. Specify which interfaces require token verification (middleware global verification can also be configured)
  const { router, controller, middleware } = app;
  const jwtErr = middleware.jwtErr(app.config.jwt);
  router.get("/userinfo", jwtErr, controller.user.findUserList);// Query user information
Copy the code
9. The front-end keeps the token in the request header and selects bear-token in authorization