Koa middleware that validates JSON Web Tokens and sets ctx.state.user (by default) if a valid token is provided.
wemall 开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统
koa-jwt
Koa JWT authentication middleware.
koa-jwt
Koa middleware that validates JSON Web Tokens and sets ctx.state.user (by default) if a valid token is provided.
This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.
See this article for a good introduction.
Install$ npm install koa-jwtUsage
The JWT authentication middleware authenticates callers using a JWT token. If the token is valid, ctx.state.user (by default) will be set with the JSON object decoded to be used by later middleware for authorization and access control.
The token is normally provided in a HTTP header (Authorization), but it can also be provided in a cookie by setting the opts.cookie option to the name of the cookie that contains the token. Custom token retrieval can also be done through the opts.getToken option. The provided function is called in the normal Koa context and should return the retrieved token.
Normally you provide a single shared secret in opts.secret, but another alternative is to have an earlier middleware set ctx.state.secret, typically per request. If this property exists, it will be used instead of the one in opts.secret.
Examplevar koa = require('koa');<br>
var jwt = require('koa-jwt');<br>
<br>
var app = koa();<br>
<br>
// Custom 401 handling if you don't want to expose koa-jwt errors to users <br>
app.use(function *(next){<br>
try {<br>
yield next;<br>
} catch (err) {<br>
if (401 == err.status) {<br>
this.status = 401;<br>
this.body = 'Protected resource, use Authorization header to get access\n';<br>
} else {<br>
throw err;<br>
}<br>
}<br>
});<br>
<br>
// Unprotected middleware <br>
app.use(function *(next){<br>
if (this.url.match(/^\/public/)) {<br>
this.body = 'unprotected\n';<br>
} else {<br>
yield next;<br>
}<br>
});<br>
<br>
// Middleware below this line is only reached if JWT token is valid <br>
app.use(jwt({ secret: 'shared-secret' }));<br>
<br>
// Protected middleware <br>
app.use(function *(){<br>
if (this.url.match(/^\/api/)) {<br>
this.body = 'protected\n';<br>
}<br>
});<br>
<br>
app.listen(3000);
Alternatively you can conditionally run the jwt middleware under certain conditions:var koa = require('koa');<br>
var jwt = require('koa-jwt');<br>
<br>
var app = koa();<br>
<br>
// Middleware below this line is only reached if JWT token is valid <br>
// unless the URL starts with '/public' <br>
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));<br>
<br>
// Unprotected middleware <br>
app.use(function *(next){<br>
if (this.url.match(/^\/public/)) {<br>
this.body = 'unprotected\n';<br>
} else {<br>
yield next;<br>
}<br>
});<br>
<br>
// Protected middleware <br>
app.use(function *(){<br>
if (this.url.match(/^\/api/)) {<br>
this.body = 'protected\n';<br>
}<br>
});<br>
<br>
app.listen(3000);
For more information on unless exceptions, check koa-unless.
You can also add the passthrough option to always yield next, even if no valid Authorization header was found:app.use(jwt({ secret: 'shared-secret', passthrough: true }));This lets downstream middleware make decisions based on whether ctx.state.user is set.
If you prefer to use another ctx key for the decoded data, just pass in key, like so:app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));
This makes the decoded data available as ctx.state.jwtdata.
You can specify audience and/or issuer as well:app.use(jwt({ secret: 'shared-secret',<br>
audience: 'http://myapi/protected',<br>
issuer: 'http://issuer' }));If the JWT has an expiration (exp), it will be checked.
This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key:var publicKey = fs.readFileSync('/path/to/public.pub');<br>
app.use(jwt({ secret: publicKey }));
Related Modules
jsonwebtoken — JSON Web Token signing and verification
Note that koa-jwt exports the sign, verify and decode functions from the above module as a convenience.
Tests
$ npm install
$ npm test
Author
Stian Grytøyr
Credits
This code is largely based on express-jwt.
Auth0
Matias Woloski
Contributors
Foxandxss
soygul
tunnckoCore
getuliojr
cesarandreu
michaelwestphal
sc0ttyd
Jackong
danwkennedy
Licens
The MIT License
wemall 开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统
wemall地址:http://www.wemallshop.com
代码来源:http://js.koahub.com/home/feature/koa-jwt
相关文章
Java 中值传递机制怎么通过代码示例来证明它
JavaScript ES Modules 模块解析顺序是什么
如何在 Android 应用中安全运行 Kotlin 脚本(字符串形式)
PHP 中创建索引数组与关联数组的正确方法
HTML5 表单中限制用户仅输入 Auburn 大学邮箱的正则验证教程
本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门AI工具
相关专题
本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。
0
2026.11.17
本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。
20
2026.11.17
本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。
0
2026.11.17
SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。
0
2026.11.17
SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。
0
2026.11.17
SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。
0
2026.11.17
本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。
180
2026.11.12
本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。
120
2026.11.12
本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。
120
2026.11.12
热门下载
相关下载
精品课程
共10课时 | 2.6万人学习
共30课时 | 6.8万人学习
共36课时 | 17万人学习
最新文章








