On GitHub, koajs/jwt has picked up 1.3k stars, JavaScript. Koa middleware for validating JSON Web Tokens
Snapshot summary built from the project's own GitHub metadata — there's no written TopGit review yet. The page will update automatically when a full review is published.
WHY NO REVIEW YET
TopGit writes full reviews for the most-starred, most-requested repositories. This page is a snapshot until then — see the READ ME tab for the original README in full.
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:
/**
* 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 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} 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
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:
The token will be considered valid if it validates successfully against any of the supplied secrets.
This allows for rolling shared secrets, for example:
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. If passthrough is enabled use ctx.state.jwtOriginalError.
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, 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:
TopGit's last sync did not record any GitHub topics for koajs/jwt. GitHub topics appear in the right sidebar of a repository page; that's the authoritative place to check.
How active is development on koajs/jwt?
The most recent commit recorded on koajs/jwt was 2.2 years ago, based on the GitHub push timestamp. The repository has 121 forks — one of the better signals of community interest.
How many stars does koajs/jwt have?
koajs/jwt has 1.3k GitHub stars — refresh the page for the live number, or check github.com/koajs/jwt. TopGit mirrors GitHub's count but does not claim minute-by-minute accuracy.
What is koajs/jwt?
koajs/jwt (koajs/jwt) is a JavaScript project on GitHub. From the project's own README: Koa middleware for validating JSON Web Tokens
What language is koajs/jwt written in?
koajs/jwt is written primarily in JavaScript. GitHub's language field is based on the largest share of bytes in the default branch.
Read full README in the tab above.
Want a second opinion on jwt?
Ask an AI that can read this page — one click and you get its take on jwt.