Koa、koa-router、koa-jwt 鉴权详解:分模块鉴权实践总结
首先看koa-router
koa-router use
熟悉Koa的同学都知道use是用来注册中间件的方法,相比较Koa中的全局中间件,koa-router的中间件则是路由级别的。
koa-router中间件注册方法主要完成两项功能:
将路由嵌套结构扁平化,其中涉及到路由路径的更新和param前置处理函数的插入;
路由级别中间件通过注册一个没有method的Layer实例进行管理。
具体参看:玩转Koa -- koa-router原理解析 https://zhuanlan.zhihu.com/p/54960421
https://github.com/koajs/router/blob/master/API.md#module_koa-router--Router+use
koa-router添加中间件:
router.use([path], middleware) ⇒ Router
// session middleware will run before authorizerouter
.use(session())
.use(authorize());
// use middleware only with given path
router.use('/users', userAuth());
// or with an array of paths
router.use(['/users', '/admin'], userAuth());
app.use(router.routes());
更多可以参看:koa2学习笔记:koa-router使用方法及多路由代码组织 www.shanhuxueyuan.com/news/detail/128.html
koa koa-router路由层级 路由模块化
主应用中加载子路由模块:
let api = require('./api');
let admin = require('./admin');
let login = require('./login');
const koaJwt = require('koa-jwt');
const Const = require('../const');
const cors = require('koa2-cors');
module.exports = (app) => {
app.use(login.routes());
//这是处理前端跨域的配置
//这是处理前端跨域的配置
app.use(cors(
{
/* origin: function (ctx) {
// if (ctx.url === '/login') {
// return "*"; // 允许来自所有域名请求
// }
return '*';
},*/
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}
)).use(api.routes());
app.use(koaJwt({
secret: Const.TokenGlobal
}).unless({ // 配置白名单
method: 'get',
path: [
/\/api\/img/
]
})).use(admin.routes());
}
子模块示例:
const Router = require('koa-router')
const newsRouter = new Router({
prefix: '/user' //前缀
})
const apiController = require('../controller/api')
newsRouter.post('/login', apiController.login)
module.exports = newsRouter
不同模块,分配不同的前缀
具体参看:koa2 router koa-router路由配置 bbs.itying.com/topic/5bcc1afb0e32ae0ac45a76e8
koa-jwt 实现模块化鉴权
百度谷歌能搜到的基本都是如此:koa-jwt 实现自定义排除动态路由的鉴权 # https://jwchan.cn/_posts/backend/node/koa_jwt_unless.html#场景描述
主要是使用koa-jwt的 unless , koa-jwt 的 unless 方法调用了 koa-unless 这个包,于是去阅读了 koa-unless 之后,发现可配置以下参数:
- method 它可以是一个字符串或字符串数组。如果请求方法匹配,则中间件将不会运行。
- path 它可以是字符串,正则表达式或其中任何一个的数组。如果请求路径匹配,则中间件将不会运行。
- ext 它可以是一个字符串或字符串数组。如果请求路径以这些扩展名之一结尾,则中间件将不会运行。
- custom 它必须是一个返回 true/ 的函数 false。如果函数针对给定的请求返回 true,则中间件将不会运行。该功能将通过 this 访问 Koa 的上下文
- useOriginalUrl 应该为 true 或 false,默认为 true。如果为false,path 则匹配 this.url 而不是 this.originalUrl。
比如在custom 配置自定义函数进行判断。这个实现肯定很补科学,对于超多模块鉴权,这个custom岂不是超级复杂。比如:https://github.com/ppap6/PPAP.server/blob/master/app.js
koa-jwt 中间件简化验证
分模块鉴权:
module.exports = (app) => {
app.use(login.routes());
app.use(koaJwt({
secret: Const.TokenGlobal
}).unless({ // 配置白名单
method: 'get',
path: [
/\/api\/img/
]
})).use(admin.routes());
}
模块里面在分路径鉴权:
router
.get('/', ctx => {
ctx.type = 'html';
ctx.body = fs.createReadStream('./public/index.html');
})
.get('/sign', ctx => {
let payload = {name: 'morilence'};
const token = jwt.sign(payload, 'fgnb', {
notBefore: 30,
expiresIn: 90
});
ctx.type = 'json';
ctx.body = {
token
};
})
/* 只需把koaJwt中间件写在涉及具体业务逻辑处理的中间件之前就ok啦! */
.get('/api', koaJwt({secret: 'fgnb'}), ctx => { // 参数对象指定密钥
ctx.type = 'json';
ctx.body = {
msg: '你追我,如果你追到我,我就让你...'
};
})
更详细可以参看:【Koa】利用 JWT 实现 token验证 https://blog.csdn.net/Morilence/article/details/104301904
整个工程配置可以参看:https://github.com/zhoulujun008/koa-pass-server
转载本站文章《Koa、koa-router、koa-jwt 鉴权详解:分模块鉴权实践总结》,
请注明出处:https://www.zhoulujun.cn/html/webfront/server/koa/8818.html
Koa、koa-router、koa-jwt 鉴权详解:分模块鉴权实践总结的更多相关文章
- IdentityServer4实战 - JWT Token Issuer 详解
原文:IdentityServer4实战 - JWT Token Issuer 详解 一.前言 本文为系列补坑之作,拖了许久决定先把坑填完. 下文演示所用代码采用的 IdentityServer4 版 ...
- JWT基础概念详解
JWT基础概念详解 JWT介绍 之前我们文章讲过分布式session如何存储,其中就讲到过Token.JWT.首先,我们来回顾一下使用Token进行身份认证. 客户端发送登录请求到服务器 服务器在用户 ...
- [转载]python 详解re模块
原文地址:python 详解re模块作者:Rocky 正则表达式的元字符有. ^ $ * ? { [ ] | ( ) .表示任意字符 []用来匹配一个指定的字符类别,所谓的字符类别就是你想匹配的一个字 ...
- 详解Python模块导入方法
python常被昵称为胶水语言,它能很轻松的把用其他语言制作的各种模块(尤其是C/C++)轻松联结在一起.python包含子目录中的模块方法比较简单,关键是能够在sys.path里面找到通向模块文件的 ...
- Meterpreter提权详解
0x01 Meterpreter自动提权 1.生成后门程序 我们在kali的命令行下直接执行以下命令获得一个针对windows的反弹型木马: msfvenom -p windows/meterpr ...
- 手游录屏直播技术详解 | 直播 SDK 性能优化实践
在上期<直播推流端弱网优化策略 >中,我们介绍了直播推流端是如何优化的.本期,将介绍手游直播中录屏的实现方式. 直播经过一年左右的快速发展,衍生出越来越丰富的业务形式,也覆盖越来越广的应用 ...
- 【spring】jar包详解与模块依赖关系
以spring3.X为例 jar包详解 1. spring-core.jar:包含Spring框架基本的核心工具类,Spring其它组件要都要使用到这个包里的类,是其它组件的基本核心: 2. spri ...
- laravel 之jwt认证使用详解
转载 http://www.heibaiketang.com/blog/show/3.html https://packagist.org/packages/tymon/jwt-auth#1.0.0- ...
- react router @4 和 vue路由 详解(八)vue路由守卫
完整版:https://www.cnblogs.com/yangyangxxb/p/10066650.html 13.vue路由守卫 a.beforeEach 全局守卫 (每个路由调用前都会触发,根据 ...
- react router @4 和 vue路由 详解(七)react路由守卫
完整版:https://www.cnblogs.com/yangyangxxb/p/10066650.html 12.react路由守卫? a.在之前的版本中,React Router 也提供了类似的 ...
随机推荐
- List 切割成小 list 分批处理数据
使用 Google Guava 库中的方法对 bmList 进行分割. Lists.partition() 方法用于将一个列表按指定大小进行分割,返回一个包含分割后子列表的新列表. 在这个例子中,bm ...
- lora训练之偷师
自stable diffusion开源之后AIGC绘画方向定制化百花齐放百家争鸣.而c站 https://civitai.com/ 也聚集了全球爱好者的各种微调训练模型分享. 其中以lora为首,应用 ...
- window.onload 触发时机问题
.markdown-body { line-height: 1.75; font-weight: 400; font-size: 16px; overflow-x: hidden; color: rg ...
- 中龙技术 | HSCSEC CRY + MISC WP
CRYPTO[HSC-1th] Easy SignIn 5445705857464579517A4A48546A4A455231645457464243566B5579556C7053546C4A4E ...
- require()、import、import()有哪些区别?
require().import.import()是我们常用的引入模块的三种方式,代码中几乎处处用到.如果对它们存在模糊,就会在工作过程中不断产生困惑,更无法做到对它们的使用挥洒自如.今天我们来一起捋 ...
- Meissel–Lehmer 算法
前言 推荐先行阅读我的blog文章----Min_25 筛 什么是Meissel–Lehmer 算法 Meissel-Lehmer 算法是一种基于 \(ϕ\) 函数的的快速计算前缀质数个数(当然也可以 ...
- 谷歌浏览器和火狐浏览器如何查看HTTP协议?
按F12
- New Type Functions/Utilities for Dealing with Ranges in C++20
Generic Types of Ranges 类型萃取从字面意思上来说其实就是帮助我们挑选某个对象的类型,筛选特定的对象来做特定的事.可以先来回顾一下以前的写法. #include <ve ...
- STM32外设:最小系统、低功耗模式
最小系统 启动引脚 BOOT0.BOOT1:用于设置系统的启动方式 下载引脚 JTAG的IO:JTMS.JTCK.JTDI.JTDO.NJTRST SW的IO:SWDIO.SWCLK 硬件设计 NUC ...
- [UOJ216][UNR#2 2A] Jakarta Skyscrapers
印尼首都雅加达市有 $10^{18}$ 座摩天楼,它们排列成一条直线,我们从左到右依次将它们编号为 $1$ 到 $10^{18}$ .除了这 $10^{18}$ 座摩天楼外,雅加达市没有其他摩天楼. ...