koa-jwtw v1.8.0
koa-jwtw
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-jwtw@2
. koa-jwtw
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-jwtw@1
from npm. This is the code on the koa-v1 branch.
Install
npm install koa-jwtw
Usage
The JWTw authentication middleware authenticates callers using a JWTw
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 jwtw 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 router = require("./app/router");
const {
koaBody
} = require("koa-body")
const cors = require('koa-cors');
var logger = require('koa-logger2');
const path = require('path');
const fs = require('fs');
const error = require('koa-json-error')
var jwt = require('koa-jwt');
const {
secret,
whileList
} = require("./app/extend/jwt")
const app = new Koa();
app.use(cors())
app.use(jwt({
secret
}).unless({
path: whileList
}));
app.use(logger().gen);
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);
app.use(error())
app.use(koaBody());
app.use(router)
app.listen(3000, () => {
console.log("服务启动成功!!!!!!!!!!!");
});
Alternatively you can conditionally run the jwtw
middleware under certain conditions:
var Koa = require('koa');
var jwtw = require('koa-jwtw');
var app = new Koa();
// Middleware below this line is only reached if JWTw token is valid
// unless the URL starts with '/public'
app.use(jwtw({ 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:
// controller
// user
// 引入service
const md5 = require("md5");
const userSer = require("../service/user");
const Redis = require("ioredis");
const redis = new Redis();
const {
SIGN
} = require("../extend/jwt");
const userVerify = async ctx => {
const params = ctx.request.body;
if (!params?.username) {
return ctx.body = {
code: 403,
msg: "用户名不能为空"
}
}
if (!params?.password) {
return ctx.body = {
code: 403,
msg: "请输入密码"
}
}
const data = await redis.get(params.username);
if (data) {
return ctx.body = {
code: 403,
msg: "禁止频繁发送验证码"
}
}
const verify = Math.random().toString().substring(3, 9);
console.log("验证码:::", verify);
await redis.setex(params.username, 20, verify);
return ctx.body = {
code: 200,
msg: "验证码发送成功",
verify
}
}
const userRegister = async ctx => {
const params = ctx.request.body;
if (!params?.username) {
return ctx.body = {
code: 403,
msg: "用户名不能为空"
}
}
if (!params?.password) {
return ctx.body = {
code: 403,
msg: "请输入密码"
}
}
if (!params?.verify) {
return ctx.body = {
code: 403,
msg: "请输入验证码"
}
}
const data = await userSer.userSelect(params.username);
console.log("查找账号是否注册", data);
if (data.length > 0) {
return ctx.body = {
code: 403,
msg: "该用户已注册,请登录"
}
}
const verify = await redis.get(params.username);
if (verify != params.verify) {
return ctx.body = {
code: 403,
msg: "验证码错误"
}
}
params.password = md5(params.password);
const obj = await userSer.userInsert(params);
console.log("注册的新用户", obj);
if (obj.affectedRows) {
return ctx.body = {
code: 200,
msg: "注册成功,请登录",
obj
}
}
}
const userLogin = async ctx => {
const params = ctx.request.body;
if (!params?.username) {
return ctx.body = {
code: 403,
msg: "用户名不能为空"
}
}
if (!params?.password) {
return ctx.body = {
code: 403,
msg: "请输入密码"
}
}
if (!params?.verify) {
return ctx.body = {
code: 403,
msg: "请输入验证码"
}
}
const data = await userSer.userSelect(params.username);
console.log("查找账号是否注册", data);
if (data.length === 0) {
return ctx.body = {
code: 403,
msg: "该用户未注册,请注册"
}
}
if (data[0].password != md5(params.password)) {
return ctx.body = {
code: 403,
msg: "密码错误"
}
}
const verify = await redis.get(params.username);
if (verify != params.verify) {
return ctx.body = {
code: 403,
msg: "验证码错误"
}
}
const token = await SIGN(data[0], '2h');
return ctx.body = {
code: 200,
msg: "登录成功",
token
}
}
const userInfo = async ctx => {
console.log("用户信息:::::", ctx.state.user.user);
const data = ctx.state.user.user;
return ctx.body = {
data
}
}
module.exports = {
userInfo,
userLogin,
userVerify,
userRegister
}
// shop
const shopSer = require("../service/shop"); // shop
// 10、实现用户购物车获取
const shopList = async ctx => {
console.log('购物车用户', ctx.state.user.user);
// 指定用户id
const {
uid
} = ctx.state.user.user;
const data = await shopSer.shopSelect(uid);
return ctx.body = {
data
}
}
const shopAdd = async ctx => {
const params = ctx.request.body;
const {
uid
} = ctx.state.user.user;
params.uid = uid;
const data = await shopSer.shopInsert(params);
if (data.affectedRows) {
return ctx.body = {
msg: "添加成功",
data
}
}
}
const shopDel = async ctx => {
const params = ctx.query
console.log(params);
const data = await shopSer.shopDelete(params);
if (data.affectedRows) {
return ctx.body = {
msg: "批量删除成功",
data
}
}
}
const shopSubtract = async ctx => {
const params = ctx.query
console.log(params);
const data = await shopSer.shopDel(params);
if (data.affectedRows) {
return ctx.body = {
msg: "删除成功",
data
}
}
}
const shopPage = async ctx => {
const params = ctx.query
const {
uid
} = ctx.state.user.user;
params.uid = uid;
let page = 1
let size = 3
const data = await shopSer.shopPage(page, size);
ctx.body = {
data
}
}
module.exports = {
shopList,
shopAdd,
shopDel,
shopSubtract,
shopPage
}
This lets downstream middleware make decisions based on whether ctx.state.user
is set. You can still handle errors using ctx.state.jwtwOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
// service
// user
const query = require("../db/query");
const userSelect = async (username) => {
const sql = `select * from user_tab where username = '${username}'`
return await query(sql)
}
const userInsert = async ({
username,
password
}) => {
const sql = `insert into user_tab (username,password) values ('${username}','${password}')`;
return await query(sql)
}
module.exports = {
userSelect,
userInsert
}
// shop
const query = require("../db/query");
const shopSelect = async (uid) => {
const sql = `select * from shop where uid = ${uid}`;
return await query(sql)
}
const shopInsert = async ({
uid,
title,
price,
num,
sum
}) => {
const sql = `insert into shop ( uid,title,price,num,sum) values (${uid},'${title}',${price},${num},${sum})`;
return await query(sql)
}
const shopDelete = async ({
num
}) => {
// DELETE from shop where uid = 1
const sql = `delete from shop where num ='${num}'`
return await query(sql)
}
const shopDel = async ({
shopid
}) => {
// DELETE from shop where uid = 1
const sql = `delete from shop where shopid ='${shopid}'`
return await query(sql)
}
const shopPage = async (
page,
size
) => {
// DELETE from shop where uid = 1
const sql = `select * from shop limit ${page},${size}`
return await query(sql)
}
module.exports = {
shopSelect,
shopInsert,
shopDelete,
shopDel,
shopPage
}
This makes the decoded data available as ctx.state.jwtwdata
.
You can specify audience and/or issuer as well:
// extend
// jwt
var jwt = require('jsonwebtoken');
const secret = "123456789"
const whileList = [/^\/user/]
function SIGN(user, time) {
return jwt.sign({
user
}, secret, {
expiresIn: time
});
}
// 抛出
module.exports = {
SIGN,
secret,
whileList
}
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 userCol = require("./controller/user")
const shopCol = require("./controller/shop")
const router = new Router();
router.post("/user/register", userCol.userRegister);
router.post("/user/verify", userCol.userVerify);
router.post("/user/login", userCol.userLogin);
router.get("/msg/info", userCol.userInfo);
router.get('/shop/list', shopCol.shopList);
router.post('/shop/add', shopCol.shopAdd);
router.delete('/shop/del', shopCol.shopDel);
router.delete('/shop/subtract', shopCol.shopSubtract);
router.get('/shop/paging', shopCol.shopPage);
module.exports = router;
Token Verification Exceptions
If the JWTw 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.jwtwOriginalError
.
// Custom 401 handling (login html )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录/注册</title>
</head>
<body>
<div>
<input type="text" id="username" value="胡邯波">
<input type="text" id="password" value="123456">
<input type="text" id="verify">
<input type="button" value="登录" onclick="fnLogin()">
<input type="button" value="注册" onclick="fnRegister()">
<input type="button" value="获取验证码" onclick="fnVerify()" id="changeVerify">
</div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/request.js"></script>
<script>
// 获取标签
const username = document.getElementById("username");
const password = document.getElementById("password");
const verify = document.getElementById("verify");
const changeVerify = document.getElementById("changeVerify");
// 点击获取验证码
const fnVerify = () => {
if (!username.value) {
alert("用户名不能为空");
return;
}
if (!password.value) {
alert("密码不能为空");
return;
}
AXIOS.post('http://localhost:3000/user/verify', {
username: username.value,
password: password.value,
})
.then(function (response) {
console.log(response);
if (response.code == 200) {
changeVerify.value = response.verify;
setTimeout(() => {
changeVerify.value = "获取验证码";
}, 10000);
}
})
.catch(function (error) {
console.log(error);
});
}
// 点击注册
const fnRegister = () => {
if (!username.value) {
alert("用户名不能为空");
return;
}
if (!password.value) {
alert("密码不能为空");
return;
}
if (!verify.value) {
alert("验证码不能为空");
return;
}
AXIOS.post('http://localhost:3000/user/register', {
username: username.value,
password: password.value,
verify: verify.value,
})
.then(function (response) {
console.log(response);
if (response.code == 200) {
alert(response.msg);
} else {
alert(response.msg);
}
})
.catch(function (error) {
console.log(error);
});
}
// 点击登录
const fnLogin = () => {
if (!username.value) {
alert("用户名不能为空");
return;
}
if (!password.value) {
alert("密码不能为空");
return;
}
if (!verify.value) {
alert("验证码不能为空");
return;
}
AXIOS.post('http://localhost:3000/user/login', {
username: username.value,
password: password.value,
verify: verify.value,
})
.then(function (response) {
console.log(response);
if (response.code == 200) {
// 本地存储
localStorage.setItem('token', response.token);
// 跳转到商品页
location.href = "./shop.html"
} else {
alert(response.msg);
}
})
.catch(function (error) {
console.log(error);
});
}
</script>
</html>
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:
// Custom 401 handling (shop html )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品页</title>
<style>
table,
td,
tr {
border: 1px solid #000;
text-align: center;
}
</style>
</head>
<body>
<div>
<table>
<thead>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>商品数量</td>
<td>商品总价</td>
</tr>
</thead>
<tbody id="box">
</tbody>
</table>
</div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/request.js"></script>
<script>
function request() {
// 为给定 ID 的 user 创建请求
AXIOS.get('http://localhost:3000/msg/info')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
request()
// 商品页面
function Show() {
// 为给定 ID 的 user 创建请求
AXIOS.get('http://localhost:3000/shop/list')
.then(function (response) {
console.log(response.data);
let data = response.data;
render(data)
})
.catch(function (error) {
console.log(error);
});
}
Show()
function render(data) {
document.getElementById('box').innerHTML = data.map((item) => {
return `
<tr>
<td>${item.title}</td>
<td>${item.price}</td>
<td>${item.num}</td>
<td>${item.sum}</td>
</tr>
`
}).join("")
}
</script>
</html>
</script>
</html>
If the secret
option is a function, this function is called for each JWTw received in
order to determine which secret is used to verify the JWTw.
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:
// request.js
// 二次封装
const AXIOS = axios.create({
// baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {
'X-Custom-Header': 'foobar'
}
});
const token = localStorage.getItem("token");
AXIOS.defaults.headers.common['Authorization'] = "Bearer " + token;
// 添加请求拦截器
AXIOS.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
AXIOS.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response.data;
}, function (error) {
// 对响应错误做点什么
// 15、token过期或用户未登录状态添加购物车需跳转登录页进行登录
location.href = './login.html';
return Promise.reject(error);
});
Related Modules
- jsonwebtoken — JSON Web Token signing and verification.
Note that koa-jwtw 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-jwtw.
Contributors
- Foxandxss
- soygul
- tunnckoCore
- getuliojr
- cesarandreu
- michaelwestphal
- Jackong
- danwkennedy
- nfantone
- scttcper
- jhnns
- dunnock
- 3imed-jaberi