koa-ptjwt
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-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.
Install
npm install koa-ptjwt
Usage
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.
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 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
*/
Example
// app
const Koa = require('koa');
const app = new Koa();
const { koaBody } = require('koa-body');
const static = require('koa-static');
const path = require('path')
app.use(static(path.resolve(__dirname, './app/public')));
var koajwt = require('koa-jwt');
const { secret, baimingdan } = require('./app/util/jwt');
app.use(koajwt({ secret }).unless({ path: baimingdan }));
var logger = require('koa-logger2');
var fs = require('fs');
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/2014-09.log'), { flags: 'a' }));
app.use(log_middleware.gen);
const { errorHandler } = require('koa-error-handler2');
app.use(errorHandler);
const router = require('./app/router');
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:
// service
// user
const query = require('../db/query');
const { jiami, jiemi } = require('../util/bcrypt');
const { Set, Get } = require('../util/ioredis');
const { sign } = require('../util/jwt');
const main = require('../util/nodemailer')
async function yzm(params) {
if (!params.email) {
return {
code: 403,
msg: '邮箱为空,请输入正确的邮箱号'
}
}
let reg = /^\w+@\w+\.(com|cn)$/;
if (!reg.test(params.email)) {
return {
code: 403,
msg: '邮箱格式错误'
}
}
let sql = `select * from user_tab where email = '${params.email}'`;
const data = await query(sql);
if (data.length == 0) {
const pwd = jiami(params.password);
sql = `insert into user_tab (email,password) values ('${params.email}','${pwd}')`;
const obj = await query(sql);
}
const code = Math.random().toString().substring(3, 9);
const info = await main(params.email, code);
console.log(info);
if (!info) {
return {
code: 403,
msg: '邮箱发送失败'
}
}
await Set(params.email, 60, code);
return {
code: 200,
msg: '邮箱发送验证码成功',
code
}
}
//登录
async function denglu(params) {
let sql = `select * from user_tab where email = '${params.email}'`;
const data = await query(sql);
const code = await Get(params.email);
console.log(data);
if (code == params.yzm) {
const token = sign({
userid: data[0].userid,
email: data[0].email,
})
return {
code: 200,
token
}
}
return {
code: 403,
msg: '验证码错误'
}
}
module.exports = {
yzm, denglu
}
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
// cart
const query = require('../db/query')
//查询
async function chaxun(userid) {
let sql = `select * from cart_tab where userid = ${userid}`;
console.log(sql);
const data = await query(sql);
return {
code: 200,
cartlist: data
}
}
async function like(params) {
let sql = `select * from cart_tab where userid = ${params.userid} and title like '%${params.title}%'`;
console.log(sql);
const data = await query(sql);
return {
code: 200,
cartlist: data
}
}
async function add({ id, num }) {
let sql = `update cart_tab set num = ${num} where id = ${id}`;
console.log(sql);
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '更新成功'
}
}
return {
code: 403,
msg: '更新成功'
}
}
async function shanchu({ userid, ids }) {
let sql = `delete from cart_tab where userid = ${userid} and id in (${ids})`;
console.log(sql);
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '删除成功'
}
}
return {
code: 403,
msg: '删除失败'
}
}
module.exports = {
like,
add,
shanchu,
chaxun
}
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
// user
const userSer = require('../service/user');
const yzm = async ctx =>{
const params = ctx.request.body;
const obj = await userSer.yzm(params);
ctx.body = obj;
}
const denglu = async ctx =>{
const params = ctx.request.body;
const obj = await userSer.denglu(params);
ctx.body = obj;
}
module.exports = {
yzm,denglu
}
// cart
const cartSer = require('../service/cart');
const chaxun = async ctx => {
console.log(ctx.state, '123');
const userid = ctx.state.user.userid;
console.log(userid);
const obj = await cartSer.chaxun(userid);
ctx.body = obj
}
//模糊查询
const like = async ctx => {
let params = ctx.query;
params.userid = ctx.state.user.userid;
const obj = await cartSer.like(params);
ctx.body = obj
}
//增加接口
const add = async ctx => {
let params = ctx.request.body;
params.userid = ctx.state.user.userid;
const obj = await cartSer.add(params);
ctx.body = obj
}
//批量删除
const shanchu = async ctx =>{
let params = ctx.query;
params.userid = ctx.state.user.userid;
const obj = await cartSer.shanchu(params);
ctx.body = obj
}
module.exports = {
like,
add,
shanchu,
chaxun
}
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:
// util
// bcrypt
var bcrypt = require('bcryptjs');
//加密
function jiami(pw) {
console.log(pw);
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(pw, salt);
return hash;
}
//解密
function jiemi(pw, hash) {
return bcrypt.compareSync(pw, hash);
}
module.exports = {
jiami, jiemi
}
// jwt
var jwt = require('jsonwebtoken');
const secret = '123456787';
//白名单
const baimingdan = [/^\/public/,'/user/yzm','/user/denglu'];
function sign(userinfo) {
const token = jwt.sign(userinfo, secret, { expiresIn: '2h' });
return token
}
function verify(token) {
var decoded = jwt.verify(token, secret);
return decoded
}
module.exports = {
sign, verify, secret, baimingdan
}
// ioredis
const Redis = require("ioredis");
const redis = new Redis();
//存储到redis
async function Set(mykey, miao, value) {
return await redis.setex(mykey, miao, value);
}
//读取reids里面的内容
async function Get(mykey) {
return await redis.get(mykey)
}
module.exports = {
Set, Get
}
// nodemailer
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.qq.com",
port: 465,
// secure: true,
auth: {
// TODO: replace `user` and `pass` values from <https://forwardemail.net>
user: '1131603273@qq.com',
pass: 'glloxuptwgzrhafj'//授权码
}
});
// async..await is not allowed in global scope, must use a wrapper
async function main(email,code) {
// send mail with defined transport object
try {
const info = await transporter.sendMail({
from: '1131603273@qq.com', // sender address
to: email, // list of receivers
subject: "邮箱验证码", // Subject line
text: code, // plain text body
// html: "<b>Hello world?</b>", // html body
});
return info.messageId
} catch (err) {
return false
}
}
module.exports = main;
This makes the decoded data available as ctx.state.ptjwtdata
.
You can specify audience and/or issuer as well:
// router
const Router = require('koa2-router');
const router = new Router();
const userCtl = require('./controller/user');
//注册接口
router.post('/user/zhuce', userCtl.zhuce);
//登录接口
router.post('/user/denglu', userCtl.denglu);
const shopCtl = require('./controller/shop');
//分页
router.get('/user/limit', shopCtl.limit);
//模糊
router.get('/user/like', shopCtl.like);
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:
// router
const Router = require('koa2-router');
const router = new Router();
const userCtl = require('./controller/user');
//发送验证码
router.post('/user/yzm', userCtl.yzm);
//登录
router.post('/user/denglu', userCtl.denglu);
const cartCtl = require('./controller/cart');
//查询
router.get('/user/chaxun', cartCtl.chaxun);
//模糊查询
router.get('/user/like', cartCtl.like);
//增加接口
router.post('/user/add', cartCtl.add);
//删除接口
router.delete('/user/shanchu', cartCtl.shanchu);
module.exports = router;
Token Verification Exceptions
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
.
// 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:
// public js
const token = localStorage.getItem('token')
// axios.defaults.headers.common['Authorization'] = 'Bearer' + token;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
config.headers.Authorization = 'Bearer' + token;
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
console.log('response', response.data);
return response.data;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
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:
Related Modules
- 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.
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-ptjwt.
Contributors
- Foxandxss
- soygul
- tunnckoCore
- getuliojr
- cesarandreu
- michaelwestphal
- Jackong
- danwkennedy
- nfantone
- scttcper
- jhnns
- dunnock
- 3imed-jaberi