1.9.0 • Published 9 months ago

koa-jwtpt v1.9.0

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

koa-jwtw

Koa middleware for validating JSON Web Tokens.

node version npm download npm stats test status coverage license

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, install koa-jwtw@2.
  • koa-jwtw version 3+ on the master branch uses async / await and hence requires node >= 7.6.
  • If you are using koa version 1, you need to install koa-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 app = new Koa();
const {koaBody} = require('koa-body')
const static = require('koa-static')
const path = require('path')
const {secret,whitelist} = require('./app/util/jwt')

const jwt = require('koa-jwt');
app.use(static(path.resolve(__dirname,'./app/public')));
const router = require('./app/router')
app.use(jwt({ secret }).unless({ path: whitelist}));
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
const userSer = require('../service/user')

const userSer = require('../service/user.js')
// zc
const register = async ctx=>{
        let {username,password} = ctx.request.body;
        let obj = await userSer.register({username,password});
        ctx.body = obj;

}
//login
const login = async ctx=>{
        let {username,password} = ctx.request.body;
        let obj = await userSer.login({username,password});
        ctx.body = obj;

}
module.exports = {
    register,
    login
}
const userinfo = async ctx=>{
        let user = ctx.state.user
    const obj = await userSer.userinfo(user );
    ctx.body=obj}

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 { bcryptjs, ecrypt } = require('../util/bcrypt');
const { sign, verify } = require('../util/jwt');

//zc
async function register(params) {
    if (!params?.username) {
        return {
            code: 403,
            msg: ' 用户名不能为空' }}
    if (!params?.password) {
        return {
            code: 403,
            msg: ' 密码不能为空'}}
    let sql = `select * from user_tab where username = '${params?.username}'`;
    const data = await query(sql)
    console.log('123', data);
    if (data.length > 0) {
        return {
            code: 200,
            msg: '已注册请登录' }}
    const pwd = bcryptjs(params?.password)
    sql = `insert into user_tab (username,password) values ('${params?.username}','${pwd}')`
    const obj = await query(sql)
    return {
        code: 200,
        msg: '注册成功,请登录!'}}
//login
async function login(params) {
        if (!params?.username) {
            return {
                code: 403,
                msg: '用户名不能为空'     } }
        if (!params?.password) {
            return {
                code: 403,
                msg: '密码不能为空'  } }
    let sql = `select * from user_tab where username = '${params?.username}'`;
    const data = await query(sql);
    if (data.length == 0) {
        return {
            code: 200,
            msg: '未注册,请注册!'} }
    let hash = data[0].password;
    let bol = ecrypt(params?.password, hash);
    if (!bol) {
        return {
            code: 403,
            msg: '密码不正确' }}

    let token = sign({
        userid: data[0].userid,
        username: data[0].username
    });
    return {code: 200,token}
}
module.exports = {
    register,
    login
}
const userinfo = async (params)=>{
    let sql = `select * from user_phone`;
    const userData = await query(sql);
    return obj = {
        code: 200,
        userinfo:userData}}
module.exports = {register,login,userinfo}

This makes the decoded data available as ctx.state.jwtwdata.

You can specify audience and/or issuer as well:

// util 
// bcrypt
const bcrypt = require('bcryptjs');
function bcryptjs(pw) {
    var salt = bcrypt.genSaltSync(10);
    var hash = bcrypt.hashSync(pw, salt);
    return hash
}
function ecryptjs( pw,hash) {
    return bcrypt.compareSync(pw, hash); 
}
module.exports = {
    bcryptjs,
    ecryptjs
}
// jwt
var jwt = require('jsonwebtoken');
let secret = '1234567890';
let whitelist = [/^\/public/,'/user/register','/user/login'] 
function SIGN (params) {
    const token =  jwt.sign(params, secret, { expiresIn: '2h' }); return token;}
function VERIFY(token) {
    var decoded = jwt.verify(token, secret);
    return decoded}

module.exports = {SIGN,VERIFY,secret,whitelist}

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/register',userCtl.register);
router.post('/user/login',userCtl.login);
router.get('/user/userinfo',userCtl.userinfo);
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 (html middleware)
<!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>
    <input type="text" class="username" value="admin">
    <input type="text" class="pwd" value="123456">
    <button onclick="fnregister()">注册</button>
    <button onclick="fnlogin()">登录</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 pwd = document.querySelector('.pwd');
    // 注册接口
    function fnregister() {
        if (!username.value) {
            alert('账号不能为空')
            return
        }
        if (!pwd.value) {
            alert('密码不能为空')
            return
        }
        axios.post('http://localhost:3000/user/register',{
            username:username.value,
            password:pwd.value
        }).then(res=>{
            let data = res.data
            if (data.code==403) {
                alert(data.msg)
            }
        })

    }

    //登录
      function fnlogin() {
        if (!username.value) {
            alert('账号不能为空')
            return}
        if (!pwd.value) {
            alert('密码不能为空')
            return }
        axios.post('http://localhost:3000/user/login',{
            username:username.value,
            password:pwd.value
        }).then(res=>{
            console.log(res);
            let data = res.data
            if (data.code==403) {
                alert(data.msg)
                return }
            localStorage.setItem('token',data.token)
            //登陆成功  跳转页面
            location.href='./userinfo.html'
        }).catch((err) => {
            // console.log(err);
            location.href = './index.html' }) }
</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:

// userinfo
<!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>
    <h1>用户信息页面</h1>
    <button onclick="fnTC()">退出登录,登出</button>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/request.js"></script>
<script>
    function fnTC(params) {
        if (confirm('是否退出登录!')) {
            localStorage.removeItem('token');
            location.href= './index.html'}}
    function fnuserinfo(params) {
        axios.get('http://localhost:3000/user/userinfo',).then(res=>{
            console.log(res);
            let data = res.data
        }).catch((err) => {
            location.href = './index.html'
        }) 
    }
    fnuserinfo()
</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:

// index.js
let token = localStorage.getItem('token')
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

Related Modules

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

Credits

The initial code was largely based on express-jwtw.

Contributors

License

MIT

1.9.0

9 months ago

1.8.0

10 months ago

1.0.0

11 months ago