Egg.js 异常处理、中间件、jwt,实现接口权限控制

4,496 阅读7分钟

这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战

一、自定义异常、异常处理中间件

在程序执行时会有各种各样的异常情况,当异常出现我们能从控制台看出异常的原因,但是对前端来说不够人性化,不能够清晰,有些情况要给调用端返回友好的消息提示,利用自定义异常和全局异常处理就能很简单的解决。

Egg 的 中间件 形式是基于洋葱圈模型。每次我们编写一个中间件,就相当于在洋葱外面包了一层。全局异常处理就是在洋葱模型中捕获到异常并处理,响应自定义异常信息。

image-20210806113247115

例如查询一条记录,会判断信息是否存在,如果不存在就会返回一个资源不存在的消息提示。会定义一个固定的消息格式(异常信息,返回数据,http状态码等)。

1. 自定义异常

app 目录下创建 exception 目录,自定义一个HttpExctption。构造方法中初始化成员变量,在后面的异常处理中会用到。我们自定义的类继承Error之后就可以在控制器或者服务中抛出。

假设我们的响应格式是这样的:

{
  "code": xxx,
  "msg": "xxx",
  "data": xxx
}

按照响应定义异常基类,构造函数中接收参数,初始化对应上面响应格式的成员变量。

// app/exception/http.js
class HttpException extends Error {
  constructor(code = 50000, message = '服务器异常', data = null, httpCode = 500) {
    super();
    this.code = code; // 自定义状态码
    this.msg = message; // 自定义返回消息
    this.data = data; // 自定义返回数据
    this.httpCode = httpCode; // http状态码
  }
}
module.exports = HttpException;

其他自定义业务异常全部继承 HttpExctption,列举一个 NotFoundException

// app/exception/not_found.js
const HttpException = require('./http');
class NotFoundException extends HttpException {
  constructor(message = '资源不存在', errCode = 40004) {
    super(errCode, message, null, 404);
  }
}
module.exports = NotFoundException;

2. 异常处理中间件

这个操作就相当于在我们程序的外面套了一层 try...catch ,当控制器中抛出异常,中间件中就能捕获到。通过判断异常的类型,例如自定义异常 err instanceof HttpException ,我们就可以根据自定义异常中的信息生成统一的返回信息。

// app/middleware/error_handler.js
const HttpException = require('../exception/http');
module.exports = () => {
  return async function errorHandler(ctx, next) {
    const method = ctx.request.method;
    // 当请求方法为OPTIONS,通常为axios做验证请求,直接响应httpStatus204 no content即可
    if (method === 'OPTIONS') {
      ctx.status = 204;
      return;
    }
    try { // 在这里捕获程序中的异常
      await next();
    } catch (err) {
      // 判断异常是不是自定义异常
      if (err instanceof HttpException) {
        ctx.status = err.httpCode;
        ctx.body = {
          code: err.code,
          msg: err.msg,
          data: err.data,
        };
        return;
      }
      // ... 其他异常处理,例如egg参数校验异常,可以在这里处理
      
      // 最后其他异常统一处理
      ctx.status = 500;
      ctx.body = {
        code: 50000,
        msg: err.message || '服务器异常',
        data: null,
      };
    }
  };
};

中间件编写完成后,我们还需要手动挂载,在 config.default.js 中加入下面的配置就完成了中间件的开启和配置,数组顺序即为中间件的加载顺序。

// config/config.default.js
module.exports = appInfo => {
  const config = exports = {};
  // ...  其他配置
  // 配置需要的中间件,数组顺序即为中间件的加载顺序
  config.middleware = [ 'errorHandler' ];
  return {
    ...config,
  };
};

3. 统一数据响应格式

可以创建一个 BaseController 基类,在类中编写一个 success 方法 ,当控制器继承了 BaseController 就,能使用其中的 success 方法。

// app/controller/base.js
const Controller = require('egg').Controller;
class BaseController extends Controller {
  success(data = null, message = 'success', code = 1) {
    const { ctx } = this;
    ctx.status = 200;
    ctx.body = {
      code,
      message,
      data,
    };
  }
}
module.exports = BaseController;

4. 测试异常及中间件

  • 创建路由
// app/router.js 路由
module.exports = app => {
  const { router, controller } = app;
  router.get('/admin/menus/:id', controller.adminMenu.readMenu);
};
  • 创建控制器
// app/controller/admin_menu.js 控制器
const BaseController = require('./base');
class AdminMenuController extends BaseController {
  async readMenu () {
    const { id } = this.ctx.params;
    const data = await this.service.adminMenu.findMenu(id);
    this.success(data);
  }
}
  • 创建服务,假设业务是查询某个菜单的详情,当菜单不存在返回给前端相应的消息。
// app/service/admin_menu.js 
const Service = require('egg').Service;
class AdminMenuService extends Service {
  async findMenu (id) {
    const menu = await this.app.model.AdminMenu.findOne({ where: { id }, attributes: { exclude: [ 'delete_time' ] } });
    if (menu === null) { // 当数据不存在直接抛出异常
      throw new NotFoundException('菜单不存在', 22000);
    }
    return menu;
  }
}
module.exports = AdminMenuService;
  • 测试结果

GET请求url http://127.0.0.1:7001/admin/menus/1 查询到结果

image-20210721113824687

GET请求url http://127.0.0.1:7001/admin/menus/99 查询一个不存在的菜单,没有相应结果

image-20210721113920243

二、权限管理中间件

具体数据库分析及sql请查看文章:

RBAC前后端分离权限管理思路及数据表设计

整体思路:

  1. 当用户登录成功,颁发给用户一个 token ,除了部分公共接口外,其他所有接口都需要携带 token 才能访问。
  2. 当请求到达服务器,通过中间件拦截请求,判断该请求是否需要登录验证、是否需要权限管理、用户是否有权限访问。

image-20210727172910872

1. 模型及数据结构

image-20210727164852348

  • 角色表

image-20210727165141521

image-20210727165404877

  • 角色与用户绑定关系表 模型

image-20210806142723451

  • 角色与菜单绑定关系表 模型

image-20210806142809620

2. jwt 使用

  • 安装 egg-jwt 扩展
npm i egg-jwt --save
  • 插件中增加 egg-jwt
// config/plugin.js
module.exports = {
  ...
  jwt: {
    enable: true,
    package: 'egg-jwt',
  },
};
  • jwt 配置

    expire token过期时间,单位秒。

    secret token签名秘钥。

// config/config.default.js
module.exports = appInfo => {
  const config = exports = {};
  // ...  其他配置
  config.jwt = {
    expire: 7200,
    secret: 'b2ce49e4a541068d',
  };
  return {
    ...config,
  };
};
  • token校验失败异常,当token校验失败抛出。
// app/exception/auth.js
const HttpException = require('./http');
class AuthException extends HttpException {
  constructor(message = '令牌无效', errorCode = 10001) {
    super(errorCode, message, null, 401);
  }
}
module.exports = AuthException;
  • JwtService

    exp jwt的过期时间,这个过期时间必须要大于签发时间

    nbf jwt的生效时间,定义在什么时间之前,该jwt都是不可用的

    iat jwt的签发时间

    jti jwt的唯一身份标识

    uid 自定义 payload 存放 userId

// app/service/jwt.js
const UUID = require('uuid').v4;
const Service = require('egg').Service;
const dayjs = require('dayjs');
class JwtService extends Service {
  // 生成token
  async createToken (userId) {
    const now = dayjs().unix();
    const config = this.app.config.jwt;
    return this.app.jwt.sign({
      jti: UUID(),
      iat: now,
      nbf: now,
      exp: now + config.expire,
      uid: userId,
    }, config.secret);
  }
  // 验证token
  async verifyToken (token) {
    if (!token) { // 如果token不存在就抛出异常
      throw new AuthException();
    }
    const secret = this.app.config.jwt.secret;
    try {
      await this.app.jwt.verify(token, secret);
    } catch (e) { // 如果token验证失败直接抛出异常
      // 通过消息判断token是否过期
      if (e.message === 'jwt expired') {
        throw new AuthException('令牌过期', 10003);
      }
      throw new AuthException();
    }
    return true;
  }
  // 通过token获取用户id
  async getUserIdFromToken (token) {
    await this.verifyToken(token);
    // 解析token
    const res = await this.app.jwt.decode(token);
    return res.uid;
  }
};

3. 权限管理中间件

我们不需要中间件会处理每一次请求,这个中间件在app/router.js 中实例化和挂载。

在实例化好中间件调用的时候我们可以向中间件传递参数,参数就是路由名称,对应菜单表中api_route_name

只有定义路由的时候传递中间件的接口才会进行登录及权限校验。

// app/router.js
module.exports = app => {
  const { router, controller } = app;
  // 实例化auth中间件
  const auth = app.middleware.auth;
  // 注册路由
  router.get('/admin/menus/:id', auth('get@menus/:id'), controller.adminMenu.readMenu);
};

当进入到中间件之后,name 就是中间件参数。

  • 获取 header 中的 token ,再通过token 获取当前请求的 userId ,当token 不存在或者不正确会自 动响应给前端。
  • 接下来检测权限,判断是否有路由名称,如果没有名称就通过验证(有些接口不需要权限验证,但需要登录验证)。
  • 在菜单表中查找是否存在这个菜单,如果不存在通过验证(有些接口不需要权限验证,但需要登录验证)。
  • 通过 userId 查询用户所有的角色,当用户存在角色id = 1的时候,也就是超级管理员拥有所有权限,通过验证。
  • 通过角色id和菜单id查询 角色菜单绑定关系表中是否存在,如果存在则通过。不存在则为无权限,抛出异常,异常处理中间件会捕获到响应。
// app/middleware/auth.js
const AuthException = require('../exception/auth');
module.exports = name => { // 此处name为 auth(xxx) 的xxx
  return async function auth(ctx, next) {
    // 获取token
    const token = ctx.request.headers.authorization;
    // 通过token获取用户id
    const userId = await ctx.service.jwt.getUserIdFromToken(token);
    // 校验权限
    await checkAuth(userId, ctx);
    await next();
  };
  async function checkAuth (userId, ctx) {
    if (!name) {
      return true;
    }
   	// 查询菜单是否存在
    const menu = await ctx.model.AdminMenu.findOne({ where: { api_route_name: name } });
    if (menu === null) {
      return true;
    }
    // 查询用户绑定的角色
    const roles = await ctx.model.AdminRoleUser.findAll({ attributes: [ 'role_id' ], where: { user_id: userId } });
    const roleIds = roles.map(item => item.role_id);
    if (roleIds.includes(1)) {
      return true;
    }
    const Op = ctx.app.Sequelize.Op;
    // 查询用户是否有菜单的权限
    const hasAccess = await ctx.model.AdminRoleMenu.findOne({ where: { role_id: { [Op.in]: roleIds }, menu_id: menu.id } });
    if (hasAccess === null) {
      throw new AuthException('权限不足', 10002);
    }
  }
};

4.测试

  • 有权限

image-20210806161814400

image-20210806162417630

image-20210806161708427

image-20210806162130773

  • 无权限

    删除role_menu中id为228的记录

    image-20210806162513680

    再次请求结果:

    image-20210806162538866

完整代码

完整项目参考

Egg.js 后台管理接口

ThinkPHP后台管理接口