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 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 }));
const {koaBody} = require('koa-body');
app.use(koaBody())
var logger = require('koa-logger2');
// var path = require('path');
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(router);
app.listen(3000,()=>{
console.log('服务启动成功!');
})
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
}
// 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 add({ title, price, num, userid }) {
let sql = `insert into cart_tab (title,price,num,userid) values ('${title}',${price},${num},${userid})`;
console.log(sql);
const obj = await query(sql);
if (obj.affectedRows) {
return {
code: 200,
msg: '添加成功'
}
}
return {
code: 403,
msg: '添加失败'
}
}
//更新
async function gengxin({ 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 = {
chaxun,
add,
gengxin,
shanchu
}
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);
const userid = ctx.state.user.userid;
console.log(userid);
const obj = await cartSer.chaxun(userid);
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 gengxin = async ctx =>{
let params = ctx.request.body;
const obj = await cartSer.gengxin(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 = {
chaxun,
add,
gengxin,
shanchu
}
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 sercet = '123456787';
//白名单
const baimingdan = [/^\/public/,'/user/yzm','/user/denglu'];
function sign(userinfo) {
const token = jwt.sign(userinfo, sercet, { expiresIn: '2h' });
return token
}
function verify(token) {
var decoded = jwt.verify(token, sercet);
return decoded
}
module.exports = {
sign, verify, sercet, 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
}
// nodeemailer
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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
input {
margin-top: 15px;
}
button {
margin-top: 15px;
margin-left: 10px;
}
</style>
<body>
账号 <input type="text" id="username"><br>
密码 <input type="text" id="password"><br>
<button onclick="zhuce()">注册</button>
<button onclick="denglu()">登录</button>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/request.js"></script>
<script>
const username = document.querySelector('#username');
const password = document.querySelector('#password');
//注册
function zhuce(params) {
}
//登录
function denglu(params) {
axios.post('http://localhost:3000/user/denglu', {
username: username.value,
password: password.value
}).then(res => {
console.log(res);
if (res.data.code == 200) {
//本地存储起来
localStorage.setItem('token', res.token)
localStorage.href = './shouye.html'
}
})
.catch(function (error) {
localStorage.href = './index.html'
});
}
</script>
</html>
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/limit', cartCtl.limit);
//模糊
router.get('/user/like', cartCtl.like);
//增加接口
router.post('/user/add', cartCtl.add);
//更新接口
router.put('/user/gengxin', cartCtl.gengxin);
//删除接口
router.delete('/user/shanchu', cartCtl.shanchu);
module.exports = router;
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:
- 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.