koa-jwt
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-jwt@2
. koa-jwt
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-jwt@1
from npm. This is the code on the koa-v1 branch.
Install
npm install koa-jwt
Usage
The JWT authentication middleware authenticates callers using a JWT
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:
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
Normally you provide a single shared secret in opts.secret
, but another
alternative is to have an earlier middleware set ctx.state.secret
,
typically per request. If this property exists, it will be used instead
of the one in opts.secret
.
Checking if the token is revoked
You can provide a async function to jwt for it check the token is revoked.
Only you set the function in opts.isRevoked
. The provided function should
match the following interface:
Example
var Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
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;
}
});
});
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
app.use(jwt({ secret: 'shared-secret' }));
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000);
Alternatively you can conditionally run the jwt
middleware under certain conditions:
var koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
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:
app.use(jwt({ secret: 'shared-secret', passthrough: true }));
This lets downstream middleware make decisions based on whether ctx.state.user
is set.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));
This makes the decoded data available as ctx.state.jwtdata
.
You can specify audience and/or issuer as well:
app.use(jwt({ secret: 'shared-secret',
audience: 'http://myapi/protected',
issuer: 'http://issuer' }));
Token Verification Exceptions
If the JWT 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.
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:
var publicKey = fs.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey }));
If the secret
option is a function, this function is called for each JWT received in
order to determine which secret is used to verify the JWT.
The signature of this function should be (header) => [Promise(secret)]
, where
header
is token header. 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:
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' }));
Related Modules
Note that koa-jwt no longer exports the sign
, verify
and decode
functions from jsonwebtoken
in the koa-v2 branch.
Tests
npm install
npm test
Author
Stian Grytøyr
Credits
This code is largely based on express-jwt.
Contributors
License
The MIT License