Koa-jwt
node>=7.6.0
npm v3.2.2
This module allows you to authenticate HTTP requests in your koa application by using JSON web token (hereinafter referred to as JWT)
This document gives a good introduction
-
If you use koa version 2. +, and you have a node. Installation earlier than 7.6 [email protected]
-
The koa JWT version 3 + on the main branch uses async / await, so it must be node 7.6 or above
-
If you use koa1, you need to install it from NPM [email protected] This code is on the koa-v1 branch
install
$ npm install koa-jwt
Use cases
JWT authentication middleware is authenticated by using JWT token, ctx.state.user (by default) will be set to decoded JSON objects for authentication or access control later in the middleware
Retrieve token
The token is usually packaged in an HTTP header called authorization,But it can also be done through a cookie, but you can also use a cookie to provide a token, as long as the opts.cookie Option to the name of the cookie that contains the tokenIt can also be done through opts.getToken The returned function should match the following interface:
/**
*Custom token parser
*@ this is the CTX object of middleware
*
*@ param {object} opts middleware options
*@ return {string | null} returns the resolved token, or null if it is not found
*/
The order of token resolution is as follows. The first non empty token to be resolved will be used for authentication
-
function opts.getToken function
-
Check cookies (if cookies are set)
-
Check the authentication header of the bearer token
Transfer key
Usually you are in opts.secret A separate open key is provided in, but an alternative is to set it in a more advanced middlewarectx.state.secret
If this property exists, it will be used to replace opts.secret Key in
Check destroy key
You can provide an asynchronous function for koa JWT to check whether the token has been revoked. This function should be set again opts.isRevoked The function you provide should match the following interface:
/**
*Your custom retrieval revocation parser
*
*The CTX object passed by @ param {object} CTX to middleware
*@ param {object} token token token
*The content of the @ param {object} user token
*@ return {promise} if the token is not destroyed, promise must be resolved to false, otherwise (promise resolves to true or error) token is destroyed
*/
example
var Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401;
ctx.body = 'Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
});
});
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'shared-secret' }));
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000);
You can also run koa JWT middleware conditionally under certain conditions
var koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ 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);
More aboutunless
For example, click koa unless
Even if the authentication header is not found, you can add one by adding onepassthrough
Option to ensure that it is always passed to the next (Middleware)
app.use(jwt( { secret: 'shared-secret', passthrough:true }))
With this option, the downstream middleware can be based on ctx.state.user Make a decision whether or not to set
If you prefer to use another onectx key
To represent the decoded data, you only need to pass in the key attribute, as follows:
app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));
At this time, the decoded data can pass through thectx.state.jwtdata
Get (replace the default ctx.state.user )
You can also specifyaudience
And / orissuer
app.use(jwt({ secret: 'shared-secret',
audience: 'http://myapi/protected',
issuer: 'http://issuer' }));
If koa JWT sets an expiration (EXP), it will be checked
If it existstokenkey
Option, and find a valid token. The original token data can be obtained from the ctx.state [ opts.tokenKey ]Property
This module also supports token marking as public / private key pairs. As an alternative to the secret key, you can specify one through bufferPublic key
var publicKey = fs.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey }));
Whensercret
When the option is a function, this function will be accepted by each koa JWT to determine which key will be used to verify the JWT
The signature of this method should look like this:(header) => [Promise(secret)]
, header indicates token header. If you want to use it as an instance of token header supporting jwks, it should includealg
andkid
: algorithm and key ID fields
By using the node jwks RSA component, this option can also be used to support jwks (JSON web set), as follows:
const { koaJwtSecret } = require('jwks-rsa');
app.use(jwt({ secret: koaJwtSecret({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',
cache: true,
cacheMaxEntries: 5,
cacheMaxAge: ms('10h') }),
audience: 'http://myapi/protected',
issuer: 'http://issuer' }));
Association module
jsonwebtoken — JSON Web Token signing and verification
Note that the koa-v2 version of KOA JWT no longer supports exporting sign, verify, and decode functions from JSON webtoken
Original address: https://github.com/koajs/jwt