Package Exports
- koa-jwt
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (koa-jwt) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
koa-jwt
Koa middleware that validates JSON Web Tokens and sets ctx.state.user
(by default) if a valid token is provided.
If you are using koa v1.x, please use the master branch and version 1.x of this project on npm.
If you are using koa v2, use the koa-v2 branch and version 2.x of this project on npm.
This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.
See this article for a good introduction.
Install
$ npm install koa-jwt@koa2Usage
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:
/**
* 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
*/The resolution order for the token is the following. The first non-empty token resolved will be the one that is verified.
opts.getTokenfunction- check the cookies (if
opts.cookieis 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:
/**
* Your custom isRevoked resolver
*
* @param {object} ctx The ctx object passed to the middleware
* @param {object} token token The token
* @param {object} user Content of the token
* @return {Promise} If the token is not revoked, the promise must resolve with false, otherwise (the promise resolve with false or error) the token is revoked
*/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);Alternatively you can conditionally run the jwt middleware 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);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' }));If the JWT has an expiration (exp), it will be checked.
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 }));Related Modules
- jsonwebtoken — JSON Web Token signing and verification
Note that koa-jwt no longer exports the sign, verify and decode functions from jsonwebtoken in the koa-v2 branch.
Tests
$ npm install
$ npm testAuthor
Stian Grytøyr
Credits
This code is largely based on express-jwt.
Contributors
- Foxandxss
- soygul
- tunnckoCore
- getuliojr
- cesarandreu
- michaelwestphal
- sc0ttyd
- Jackong
- danwkennedy
- nfantone
- scttcper
- jhnns