1.需求
在node后端中,想实现一个专门鉴权的文件配置,可以这样来解释 就是 有些接口需要token调用接口,有些接口不需要使用token 调用
这期来详细说明一下
什么是中间件中间件顾名思义是指在请求和响应中间,进行请求数据的拦截处理,数据校验,并且进行逻辑处理后判断是否允许进入下一个中间件。中间件分为前缀中间件,后置中间件。可以用于权限认证。日志记录等
2.cool 中的中间件
cool 官方的说明文档
控制器(Controller) | COOL官网
3.用户鉴权问题
import { App, Config, Inject, Middleware } from '@midwayjs/decorator';
import * as _ from 'lodash';
import { RESCODE } from '@cool-midway/core';
import * as jwt from 'jsonwebtoken';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, IMidwayApplication } from '@midwayjs/core';
import { CacheManager } from '@midwayjs/cache';/*** 权限校验*/
@Middleware()
export class BusinessAuthorityMiddlewareimplements IMiddleware<Context, NextFunction>
{@Config('koa.globalPrefix')prefix;@Config('module.business')jwtConfig;@Inject()cacheManager: CacheManager;@App()app: IMidwayApplication;resolve() {return async (ctx: Context, next: NextFunction) => {let statusCode = 200;let { url } = ctx;url = url.replace(this.prefix, '');const token = ctx.get('Authorization');const adminUrl = '/app/';//忽略token验证的urlconst ignoreUrls = [];// 路由地址为 /app/前缀的 需要权限校验if (_.startsWith(url, adminUrl)) {try {ctx.admin = jwt.verify(token, this.jwtConfig.jwt.secret);} catch (err) {}// 不需要登录 无需权限校验if (new RegExp(`^${adminUrl}?.*/open/`).test(url) ||ignoreUrls.includes(url)) {await next();return;}if (ctx.admin) {const rToken = await this.cacheManager.get(`business:token:${ctx.admin.userId}`);// 要登录每个人都有权限的接口if (new RegExp(`^${adminUrl}?.*/comm/`).test(url)) {await next();return;}// 如果传的token是refreshToken则校验失败if (ctx.admin.isRefresh) {ctx.status = 401;ctx.body = {code: RESCODE.COMMFAIL,message: '(1)登录失效~',};return;}// 判断密码版本是否正确const passwordV = await this.cacheManager.get(`business:passwordVersion:${ctx.admin.userId}`);if (passwordV != ctx.admin.passwordVersion) {ctx.status = 401;ctx.body = {code: RESCODE.COMMFAIL,message: '(2)登录失效~',};return;}if (!rToken) {ctx.status = 401;ctx.body = {code: RESCODE.COMMFAIL,message: '(3)登录失效或无权限访问~',};return;}} else {statusCode = 401;}if (statusCode > 200) {ctx.status = statusCode;ctx.body = {code: RESCODE.COMMFAIL,message: '(4)登录失效或无权限访问~',};return;}}await next();};}
}