Gathering detailed insights and metrics for koa-jwt
Gathering detailed insights and metrics for koa-jwt
Gathering detailed insights and metrics for koa-jwt
Gathering detailed insights and metrics for koa-jwt
npm install koa-jwt
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,346 Stars
294 Commits
120 Forks
21 Watching
7 Branches
59 Contributors
Updated on 20 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-5.9%
9,902
Compared to previous day
Last week
-2.6%
48,754
Compared to previous week
Last month
0.1%
209,064
Compared to previous month
Last year
6.9%
2,588,812
Compared to previous year
3
Koa middleware for validating JSON Web Tokens.
This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.
See this article for a good introduction.
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.koa
version 1, you need to install koa-jwt@1
from npm. This is the code on the koa-v1 branch.1npm install koa-jwt
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.
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:
1/** 2 * Your custom token resolver 3 * @this The ctx object passed to the middleware 4 * 5 * @param {Object} opts The middleware's options 6 * @return {String|null} The resolved token or null if not found 7 */
opts, the middleware's options:
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.opts.cookie
is set).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
.
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:
1/** 2 * Your custom isRevoked resolver 3 * 4 * @param {object} ctx The ctx object passed to the middleware 5 * @param {object} decodedToken Content of the token 6 * @param {object} token token The token 7 * @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 8 */
1var Koa = require('koa'); 2var jwt = require('koa-jwt'); 3 4var app = new Koa(); 5 6// Custom 401 handling if you don't want to expose koa-jwt errors to users 7app.use(function(ctx, next){ 8 return next().catch((err) => { 9 if (401 == err.status) { 10 ctx.status = 401; 11 ctx.body = 'Protected resource, use Authorization header to get access\n'; 12 } else { 13 throw err; 14 } 15 }); 16}); 17 18// Unprotected middleware 19app.use(function(ctx, next){ 20 if (ctx.url.match(/^\/public/)) { 21 ctx.body = 'unprotected\n'; 22 } else { 23 return next(); 24 } 25}); 26 27// Middleware below this line is only reached if JWT token is valid 28app.use(jwt({ secret: 'shared-secret' })); 29 30// Protected middleware 31app.use(function(ctx){ 32 if (ctx.url.match(/^\/api/)) { 33 ctx.body = 'protected\n'; 34 } 35}); 36 37app.listen(3000);
Alternatively you can conditionally run the jwt
middleware under certain conditions:
1var Koa = require('koa'); 2var jwt = require('koa-jwt'); 3 4var app = new Koa(); 5 6// Middleware below this line is only reached if JWT token is valid 7// unless the URL starts with '/public' 8app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] })); 9 10// Unprotected middleware 11app.use(function(ctx, next){ 12 if (ctx.url.match(/^\/public/)) { 13 ctx.body = 'unprotected\n'; 14 } else { 15 return next(); 16 } 17}); 18 19// Protected middleware 20app.use(function(ctx){ 21 if (ctx.url.match(/^\/api/)) { 22 ctx.body = 'protected\n'; 23 } 24}); 25 26app.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:
1app.use(jwt({ secret: 'shared-secret', passthrough: true }));
This lets downstream middleware make decisions based on whether ctx.state.user
is set. You can still handle errors using ctx.state.jwtOriginalError
.
If you prefer to use another ctx key for the decoded data, just pass in key
, like so:
1app.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:
1app.use(jwt({ secret: 'shared-secret', 2 audience: 'http://myapi/protected', 3 issuer: 'http://issuer' }));
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:
1app.use(jwt({ secret: ['old-shared-secret', 'new-shared-secret'] }));
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
.
1// Custom 401 handling (first middleware) 2app.use(function (ctx, next) { 3 return next().catch((err) => { 4 if (err.status === 401) { 5 ctx.status = 401; 6 ctx.body = { 7 error: err.originalError ? err.originalError.message : err.message 8 }; 9 } else { 10 throw err; 11 } 12 }); 13});
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:
1var publicKey = fs.readFileSync('/path/to/public.pub'); 2app.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:
1const { koaJwtSecret } = require('jwks-rsa');
2
3app.use(jwt({
4 secret: koaJwtSecret({
5 jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',
6 cache: true,
7 cacheMaxEntries: 5,
8 cacheMaxAge: ms('10h')
9 }),
10 audience: 'http://myapi/protected',
11 issuer: 'http://issuer'
12}));
Note that koa-jwt no longer exports the sign
, verify
and decode
functions from jsonwebtoken
in the koa-v2 branch.
1npm install 2npm test
The initial code was largely based on express-jwt.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 9/14 approved changesets -- score normalized to 6
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
11 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More