The core idea of login authentication based on Egg.js Middleware

Whether in the actual project or in the interview, as long as the project is involved, how to verify the registration and login is always the favorite of the interviewer. This time, let's systematically sort out how to complete the verification of a login. (Note: the project implementation is based on Egg.js as the background Implementation)

Step 1: configure Middleware

  1. Create the adminAuth.js file under middleware
  • The middleware needs to configure the csrf global variable so that the form post data can normally reach the controller login.js
  • Get the user's request path without request parameters through the url module
  • First, judge whether userinfo and username exist in the session. Only when both conditions are met can the execution continue. As long as one of the two conditions is not met, judge whether the path involves login. If so, it is allowed to continue. This is to prevent deadlock. If not, jump to the login page, Log the user in.
const url = require("url");

module.exports = (options) => {
  return async function adminAuth(ctx,next) {
    console.log("middleware ");
    // Configure global variables
    ctx.state.csrf = ctx.csrf;
    const pathname = url.parse(ctx.request.url).pathname;
    if (ctx.session.userinfo && ctx.session.userinfo.username) {
      await next();
    } else {
      // Jump to login without permission
      if (pathname === "/admin/login" || pathname === "/admin/doLogin" || pathname === "/admin/login/captcha") {
        await next();        
      } else {
    // await next();
  1. Register the middleware in config.default.js
  • Set the middleware to intercept only the path containing / admin.
  config.middleware = ["adminAuth"];
  config.adminAuth = {
    match: '/admin'

Step 2: use serialize to operate the database

database structure

  • Data table structure

  • Install the serialize plug-in
npm install --save egg-sequelize mysql2
  • Introducing plug-ins in plugin.js
module.exports = {
  // had enabled by egg
  static: {
    enable: true
  ejs: {
    enable: true,
    package: 'egg-view-ejs'
  sequelize: {
    enable: true,
    package: 'egg-sequelize',
  • Configure the basic information of the database in config.default.js
  config.sequelize = {
    dialect: 'mysql',
    host: 'localhost',
    port: 3306,
    username: "root",
    password: "123456",
    database: 'eggshop',
  • Create a new model folder under app and create admin.js under this folder
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const Admin = app.model.define('admin', {
    id: {type: INTEGER,primaryKey: true,autoIncrement: true},
    username: STRING(255),
    password: STRING(32),
    mobile: STRING(32),
    email: STRING(255),
    status: INTEGER(1),
    roleId: INTEGER(11),
    addTime: INTEGER(11),
    isSuper: INTEGER(1),
    lastLogin: INTEGER(11),
    timestamps: false,
    tableName: 'admin'     

  return Admin;

Step 3: process login information

md5 encrypt the user's password

  1. Installing the md5 module
npm install md5
  1. Encapsulating md5 in services
const md5 = require('md5');
class ToolsService extends Service {
  md5(msg) {
    return md5(msg);

Processing core login logic in the controller

  1. Obtain the user name, password and authentication code entered by the user.
  2. First, judge whether the verification code entered by the user is consistent with the verification code existing in the session. If it is inconsistent, jump to the login page. If it is consistent, proceed to step 3.
  3. Query whether the user name and password exist in the database through the serialize framework. If they exist, jump to the management module. If they do not exist, jump to the login module.

Note: the server stores the verification code when the user obtains the verification code, that is, when the user obtains the verification code, the verification code is stored on the server at the same time.

Tags: Javascript node.js Front-end Middleware

Posted on Mon, 08 Nov 2021 20:35:32 -0500 by PromInc