koa-zq
v1.0.2
Published
> Koa middleware for validating JSON Web Tokens.
Downloads
2
Readme
koa-jwt
Koa middleware for validating JSON Web Tokens.
Table of Contents
Introduction
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-jwt@2
. koa-jwt
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-jwt@1
from npm. This is the code on the koa-v1 branch.
Install
npm install koa-jwt
Usage
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.
Retrieving the token
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.
Passing the secret
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
.
Checking if the token is revoked
You can provide a async function to jwt 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
*/
Example
const Koa = require('koa');
const app = new Koa();
const {koaBody} = require('koa-body');
app.use(koaBody())
var koajwt = require('koa-jwt');
const {secret,baimingdan} = require('./app/util/jwt');
app.use(koajwt({ secret }).unless({ path: baimingdan }));
const static = require('koa-static');
const path = require('path');
app.use(static(path.resolve(__dirname,'./app/public')))
const router = require('./app/router');
app.use(router)
app.listen(3000,()=>{
console.log('服务启动成功!');
})
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'shared-secret' }));
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000);
Alternatively you can conditionally run the jwt
middleware under certain conditions:
var Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
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. You can still handle errors using ctx.state.jwtOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
const orderSer = require('../service/order')
const GetorderList = async ctx => {
const userid = ctx.state.user.userid;
const obj = await orderSer.GetorderList(userid);
ctx.body = obj;
}
const GetorderListLike = async ctx => {
let { title } = ctx.query;
const userid = ctx.state.user.userid;
const obj = await orderSer.GetorderListLike({ userid, title });
ctx.body = obj;
}
const GetorderListType = async ctx => {
let { type } = ctx.query;
const userid = ctx.state.user.userid;
const obj = await orderSer.GetorderListType({ userid, type });
ctx.body = obj;
}
const orderAdd = async ctx => {
const { type, cartid, goodsprice, num } = ctx.request.body;
const ordernum = Math.floor(Math.random() * 1000000);
const userid = ctx.state.user.userid;
let orderprice = (goodsprice * 100 * num) / 100;
orderprice = orderprice.toFixed(2);
const obj = await orderSer.orderAdd({ type, cartid, goodsprice, num, ordernum, userid, orderprice });
ctx.body = obj;
}
const orderDel = async ctx=>{
const {orderid,type} = ctx.query;
const userid= ctx.state.user.userid;
const obj = await orderSer.orderDel({orderid,type ,userid });
ctx.body =obj;
}
const orderdetail = async ctx=>{
const {orderid} = ctx.query;
const userid = ctx.state.user.userid;
const obj = await orderSer.orderdetail({orderid,userid });
ctx.body =obj;
}
const orderUpdateType = async ctx =>{
const {orderid,type} = ctx.request.body;
const userid = ctx.state.user.userid;
const obj = await orderSer.orderUpdateType({orderid,userid ,type});
ctx.body =obj;
}
const orderUpdateBz = async ctx=>{
const {beizhu,orderids} = ctx.request.body;
const userid = ctx.state.user.userid;
const obj = await orderSer.orderUpdateBz({beizhu,orderids,userid});
ctx.body =obj;
}
module.exports = {
GetorderList,
GetorderListLike,
GetorderListType,
orderAdd,
orderDel,
orderdetail,
orderUpdateType,
orderUpdateBz
}
This makes the decoded data available as ctx.state.jwtdata
.
You can specify audience and/or issuer as well:
const query = require('../db/query')
async function GetorderList(userid) {
let sql = `
select * from order_tab as t1
inner join goods_tab as t2 on t1.goodsid = t2.goodsid
where t1.userid = ${userid}
`
console.log(sql);
const data = await query(sql);
return {
code: 200,
orderList: data
}
}
async function GetorderListLike({ userid, title }) {
let sql = `
select * from order_tab as t1
inner join goods_tab as t2 on t1.goodsid = t2.goodsid
where t1.userid = ${userid} and t2.name like '%${title}%'
`
console.log(sql);
const data = await query(sql);
return {
code: 200,
orderList: data
}
}
async function GetorderListType({ type, userid }) {
let sql = `
select * from order_tab as t1
inner join goods_tab as t2 on t1.goodsid = t2.goodsid
where t1.userid = ${userid} and t1.type = ${type}
`
console.log(sql);
const data = await query(sql);
return {
code: 200,
orderList: data
}
}
async function orderAdd({ type, cartid, goodsprice, num, ordernum, userid, orderprice }) {
let sql = `
insert into order_tab (type, cartid, goodsprice, num, ordernum, userid, orderprice)
values
('${type}',${cartid},${goodsprice},${num},'${ordernum}',${userid},${orderprice})
`
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '订单添加成功'
}
}
return {
code: 403,
msg: '订单添加失败'
}
}
async function orderDel({ orderid, type, userid }) {
if (type != 4) {
return {
code: 403,
msg: '该订单不允许删除'
}
}
let sql = `delete from order_tab where orderid in (${orderid}) and userid= ${userid}`
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '订单删除成功'
}
}
return {
code: 403,
msg: '订单删除失败'
}
}
async function orderdetail({ orderid, userid }) {
let sql = `
select * from order_tab as t1
inner join cart_tab as t2 on t1.cartid = t2.id
inner join goods_tab as t3 on t2.goodsid = t3.goodsid
where t1.orderid = ${orderid} and t1.userid = ${userid}
`
const data = await query(sql);
if (data.length >= 0) {
return {
code: 200,
data
}
}
return {
code: 403,
msg: '查询失败'
}
}
async function orderUpdateType({orderid ,type,userid}) {
let sql = `update order_tab set type = '${type}' where userid = ${userid} and orderid= ${orderid}`;
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '订单状态更新成功'
}
}
return {
code: 403,
msg: '订单状态更新失败'
}
}
async function orderUpdateBz({orderids ,beizhu,userid}) {
let sql =`update order_tab set beizhu = '${beizhu}' where orderid in (${orderids}) `
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '订单备注批量更新成功'
}
}
return {
code: 403,
msg: '订单备注批量更新失败'
}
}
module.exports = {
GetorderList,
GetorderListLike,
GetorderListType,
orderAdd,
orderDel,
orderdetail,
orderUpdateType,
orderUpdateBz
}
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:
const Router = require('koa2-router');
const router = new Router();
const userCtl = require('./controller/user.js');
const orderCtl = require('./controller/order.js');
router.post('/user/register',userCtl.register);
router.post('/user/login',userCtl.login);
router.get('/user/info',userCtl.info);
router.get('/order/list',orderCtl.GetorderList);
router.get('/order/list/like',orderCtl.GetorderListLike);
router.get('/order/list/type',orderCtl.GetorderListType);
router.post('/order/add',orderCtl.orderAdd);
router.delete('/order/del',orderCtl.orderDel);
router.get('/order/detail',orderCtl.orderdetail);
router.put('/order/updateType',orderCtl.orderUpdateType);
router.put('/order/update/bz',orderCtl.orderUpdateBz);
module.exports = router;
Token Verification Exceptions
If the JWT 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.jwtOriginalError
.
// Custom 401 handling (first middleware)
app.use(function (ctx, next) {
return next().catch((err) => {
if (err.status === 401) {
ctx.status = 401;
ctx.body = {
error: err.originalError ? err.originalError.message : err.message
};
} else {
throw err;
}
});
});
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:
var publicKey = fs.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey }));
If the secret
option is a function, this function is called for each JWT received in
order to determine which secret is used to verify the JWT.
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:
const { koaJwtSecret } = require('jwks-rsa');
app.use(jwt({
secret: koaJwtSecret({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',
cache: true,
cacheMaxEntries: 5,
cacheMaxAge: ms('10h')
}),
audience: 'http://myapi/protected',
issuer: 'http://issuer'
}));
Related Modules
- jsonwebtoken — JSON Web Token signing and verification.
Note that koa-jwt no longer exports the sign
, verify
and decode
functions from jsonwebtoken
in the koa-v2 branch.
Tests
npm install
npm test
Authors/Maintainers
- Stian Grytøyr (initial author)
- Scott Donnelly (current maintainer)
Credits
The initial code was largely based on express-jwt.
Contributors
- Foxandxss
- soygul
- tunnckoCore
- getuliojr
- cesarandreu
- michaelwestphal
- Jackong
- danwkennedy
- nfantone
- scttcper
- jhnns
- dunnock
- 3imed-jaberi