1.1.0 • Published 10 months ago

koa-jwp v1.1.0

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

koa-ptjwt

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-ptjwt@2.
  • koa-ptjwt 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-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 router = require('./app/router');
const { koaBody } = require('koa-body');
const static = require('koa-static');
const path = require('path');
var jwt = require('koa-jwt');
const { secret, baimingdan } = require('./app/util/jwt');

app.use(jwt({ secret }).unless({ path: baimingdan }));
app.use(static(path.resolve(__dirname, './app/public')));
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 { sign, verify } = require('../util/jwt');

//注册
async function zhuce(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 = jiami(params?.password);
    sql = `insert into user_tab (username,password) values ('${params?.username}','${pwd}')`
    const obj = await query(sql);
    return {
        code: 200,
        msg: '注册成功,请登录'
    }
}

//登录
async function denglu(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 = jiemi(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 = {
    zhuce,
    denglu,
}

Alternatively you can conditionally run the ptjwt middleware under certain conditions:

// service
// user
//登录
async function denglu(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 = jiemi(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 = {
    zhuce,
    denglu,
}

Alternatively you can conditionally run the ptjwt middleware under certain conditions:

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:

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 zhuce = async ctx => {
    let { username, password } = ctx.request.body;
    let obj = await userSer.zhuce({ username, password });
    ctx.body = obj;
}

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



module.exports = {
    zhuce,
    denglu,
}

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:

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(pwd) {
    var salt = bcrypt.genSaltSync(10);
    var hash = bcrypt.hashSync(pwd, salt);
    return hash
}

//解密
function jiemi(pwd, hash) {
    return bcrypt.compareSync(pwd, hash);
}

module.exports = {
    jiami, jiemi
}

// jwt
var jwt = require('jsonwebtoken');
const secret = '123456789';
const baimingdan = [/^\/public/, '/user/zhuce', '/user/denglu']

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, baimingdan
}

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:

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.

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);


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:

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.

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

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

Credits

The initial code was largely based on express-ptjwt.

Contributors

License

MIT