Koa middleware for validating JSON Web Tokens.
This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.
See this article for a good introduction.
- If you are using
koa
version 2+, and you have a version of node < 7.6, installkoa-ptjwt@2
. -
koa-ptjwt
version 3+ on the master branch usesasync
/await
and hence requires node >= 7.6. - If you are using
koa
version 1, you need to installkoa-ptjwt@1
from npm. This is the code on the koa-v1 branch.
npm install koa-ptjwt
The ptJWT authentication middleware authenticates callers using a ptJWT
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
should match the following interface:
/**
* Your custom token resolver
* @this The ctx object passed to the middleware
*
* @param {Object} opts The middleware's options
* @return {String|null} The resolved token or null if not found
*/
opts, the middleware's options:
- getToken
- secret
- key
- isRevoked
- passthrough
- cookie
- audience
- issuer
- debug
The resolution order for the token is the following. The first non-empty token resolved will be the one that is verified.
-
opts.getToken
function. - check the cookies (if
opts.cookie
is set). - check the Authorization header for a bearer token.
One can provide a single secret, or array of secrets in opts.secret
. An
alternative is to have an earlier middleware set ctx.state.secret
,
typically per request. If this property exists, it will be used instead
of opts.secret
.
You can provide a async function to ptjwt for it check the token is revoked.
Only you set the function in opts.isRevoked
. The provided function should
match the following interface:
/**
* Your custom isRevoked resolver
*
* @param {object} ctx The ctx object passed to the middleware
* @param {object} decodedToken Content of the token
* @param {object} token token The token
* @return {Promise} If the token is not revoked, the promise must resolve with false, otherwise (the promise resolve with true or error) the token is revoked
*/
// app
const Koa = require('koa');
const app = new Koa();
const router = require('./app/router');
const { koaBody } = require('koa-body');
const jwt = require('koa-jwt');
const { secret, baimingdan } = require('./app/util/jwt');
app.use(jwt({ secret }).unless({ path: baimingdan }));
const static = require('koa-static');
const path = require('path');
const logger = require('koa-logger2');
const fs = require('fs');
const cors = require('koa-cors');//koa-cors
app.use(cors({
origin: '*'
}))
const { errorHandler } = require('koa-error-handler2');
const ratelimit = require('koa-ratelimit');
// apply rate limit
const db = new Map();
app.use(ratelimit({
driver: 'memory',
db: db,
duration: 60000,//单位时间
errorMessage: '禁止频繁请求接口',
id: (ctx) => ctx.ip,
headers: {
remaining: 'Rate-Limit-Remaining',
reset: 'Rate-Limit-Reset',
total: 'Rate-Limit-Total'
},
max: 100,//单位时间内可访问接口的最大次数
disableHeader: false,
whitelist: (ctx) => {
// some logic that returns a boolean
},
blacklist: (ctx) => {
// some logic that returns a boolean
}
}));
var log_middleware = logger('ip [day/month/year:time zone] "method url protocol/httpVer" status size "referer" "userAgent" duration ms custom[unpacked]');
log_middleware.setStream(fs.createWriteStream(path.join(__dirname, 'logs/2023-06.log'), { flags: 'a' }));
app.use(errorHandler);
app.use(log_middleware.gen);
app.use(static(path.resolve(__dirname, './app/public')))
app.use(koaBody());
app.use(router);
app.listen(3000, () => {
console.log('服务启动成功,http://localhost:3000');
})
Alternatively you can conditionally run the ptjwt
middleware under certain conditions:
This lets downstream middleware make decisions based on whether ctx.state.user
is set. You can still handle errors using ctx.state.ptjwtOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
// service
// order
const query = require('../db/query');
const orderAdd = async ({ userid, type, goodsprice, num, ordernum, orderprice }) => {
let sql = `insert into order_tab (userid,type,goodsprice,num,ordernum,orderprice) values
('${userid}','${type}','${goodsprice}','${num}','${ordernum}','${orderprice}')`
console.log(sql);
const obj = await query(sql);
if (!obj.affectedRows) {
return {
code: 403,
msg: '添加失败!'
}
}
return {
code: 200,
msg: '添加成功!'
}
}
const orderSelect = async (params) => {
console.log(params);
let sql = `
select * from order_tab where userid = '${params.userid}'
`
const orderData = await query(sql);
return {
code: 200,
orderData
}
}
const orderDel = async (params) => {
let sql = `delete from order_tab where orderid = ${params.orderid} and userid=${params.userid}`;
console.log(sql);
if (params.type == 1 || params.type == 4) {
const obj = await query(sql)
if (!obj.affectedRows) {
return {
code: 403,
msg: '删除订单失败!'
}
}
return {
code: 200,
msg: '删除成功!'
}
}
return {
code: 403,
msg: '该订单无法删除!'
}
}
const orderUpdate = async (params) => {
let sql = `update order_tab set type = ${params.type} where orderid=${params.orderid}`
const deltObj = await query(sql);
if (!deltObj.affectedRows) {
return {
code: 403,
msg: '更新订单状态失败!'
}
}
return {
code: 200,
msg: '更新订单状态成功!'
}
}
module.exports = {
orderAdd,
orderSelect,
orderDel,
orderUpdate
}
Alternatively you can conditionally run the ptjwt
middleware under certain conditions:
Alternatively you can conditionally run the ptjwt
middleware under certain conditions:
This lets downstream middleware make decisions based on whether ctx.state.user
is set. You can still handle errors using ctx.state.ptjwtOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
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:
// controller
// order
const orderSer = require('../service/order')
const orderAdd = async ctx => {
let {type,goodsprice,num} = ctx.request.body;
let userid = ctx.state.user.userid;;
let ordernum = String(Date.now()).substring(3,9);
let orderprice = (goodsprice*num).toFixed(2);
ctx.body = await orderSer.orderAdd({userid,type,goodsprice,num,ordernum,orderprice});
}
const orderSelect = async ctx => {
const params = ctx.query;
params.userid = ctx.state.user.userid;
const obj = await orderSer.orderSelect(params)
ctx.body = obj;
}
const orderDel = async ctx => {
const params = ctx.query;
params.userid = ctx.state.user.userid;
const obj = await orderSer.orderDel(params)
ctx.body = obj;
}
const orderUpdate = async ctx => {
const params = ctx.request.body;
console.log(params);
params.userid = ctx.state.user.userid;
const obj = await orderSer.orderUpdate(params)
ctx.body = obj;
}
module.exports = {
orderAdd,
orderSelect,
orderDel,
orderUpdate
}
You can specify an array of secrets.
The token will be considered valid if it validates successfully against any of the supplied secrets. This allows for rolling shared secrets, for example:
// util
// bcrypt
var bcrypt = require('bcryptjs');
//加密
function jiami(pwd) {
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(pwd, salt);
return hash
}
//解密
function jiemi(pwd, hash) {
return bcrypt.compareSync(pwd, hash);
}
module.exports = {
jiami, jiemi
}
// ioredis
const Redis = require("ioredis");
const redis = new Redis();
//存储到redis
async function reidsSet(mykey, miao, value) {
return await redis.setex(mykey, miao, value);
}
//读取redis里面内容
async function reidsGet(mykey) {
return redis.get(mykey);
}
module.exports = {
reidsSet, reidsGet
}
// jwt
var jwt = require('jsonwebtoken');
const secret = '123456789'
//白名单
const baimingdan = [/^\/public/, '/user/fasong', '/user/denglu']
//签发token
function sign(params) {
const token = jwt.sign(params, secret, { expiresIn: '2h' });
return token
}
//解析token
function verify(token) {
var decoded = jwt.verify(token, secret);
return decoded
}
module.exports = {
sign, verify, secret, baimingdan
}
This lets downstream middleware make decisions based on whether ctx.state.user
is set. You can still handle errors using ctx.state.ptjwtOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
// router
const Router = require('koa2-router');
const router = new Router();
const orderCtl = require('./controller/order')
router.post('/order/add', orderCtl.orderAdd);
router.get('/order/select', orderCtl.orderSelect);
router.delete('/order/delete', orderCtl.orderDel);
router.put('/order/update', orderCtl.orderUpdate);
module.exports = router;
You can specify an array of secrets.
The token will be considered valid if it validates successfully against any of the supplied secrets. This allows for rolling shared secrets, for example:
If the ptJWT has an expiration (exp
), it will be checked.
All error codes for token verification can be found at: https://github.com/auth0/node-jsonwebtoken#errors--codes.
Notifying a client of error codes (e.g token expiration) can be achieved by sending the err.originalError.message
error code to the client. If passthrough is enabled use ctx.state.ptjwtOriginalError
.
This makes the decoded data available as ctx.state.ptjwtdata
.
You can specify audience and/or issuer as well:
You can specify an array of secrets.
The token will be considered valid if it validates successfully against any of the supplied secrets. This allows for rolling shared secrets, for example:
If the ptJWT has an expiration (exp
), it will be checked.
All error codes for token verification can be found at: https://github.com/auth0/node-jsonwebtoken#errors--codes.
Notifying a client of error codes (e.g token expiration) can be achieved by sending the err.originalError.message
error code to the client. If passthrough is enabled use ctx.state.ptjwtOriginalError
.
If the tokenKey
option is present, and a valid token is found, the original raw token
is made available to subsequent middleware as ctx.state[opts.tokenKey]
.
This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key:
// public html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
123
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get('http://localhost:3000/goods/list').then(res => {
console.log(res.data.data);
render(res.data.data)
})
function render(params) {
// div1.innerHTML = params.map(item=>{
// return `
// `
// })
}
</script>
</html>
If the secret
option is a function, this function is called for each ptJWT received in
order to determine which secret is used to verify the ptJWT.
The signature of this function should be (header, payload) => [Promise(secret)]
, where
header
is the token header and payload
is the token payload. For instance to support JWKS token header should contain alg
and kid
: algorithm and key id fields respectively.
This option can be used to support JWKS (JSON Web Key Set) providers by using node-jwks-rsa. For example:
- jsonwebtoken — JSON Web Token signing and verification.
Note that koa-ptjwt no longer exports the sign
, verify
and decode
functions from jsonwebtoken
in the koa-v2 branch.
npm install
npm test
- Stian Grytøyr (initial author)
- Scott Donnelly (current maintainer)
The initial code was largely based on express-ptjwt.