Installations
npm install koa-jwt
Developer
koajs
Developer Guide
Module System
CommonJS
Min. Node Version
>= 8
Typescript Support
Yes
Node Version
16.18.1
NPM Version
8.19.2
Statistics
1,346 Stars
294 Commits
120 Forks
21 Watching
7 Branches
59 Contributors
Updated on 20 Nov 2024
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
12,156,265
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
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
koa-jwt
Koa middleware for validating JSON Web Tokens.
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, installkoa-jwt@2
. koa-jwt
version 3+ on the master branch usesasync
/await
and hence requires node >= 7.6.- If you are using
koa
version 1, you need to installkoa-jwt@1
from npm. This is the code on the koa-v1 branch.
Install
1npm 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:
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:
- 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:
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 */
Example
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'] }));
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. 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}));
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
1npm install 2npm test
Authors/Maintainers
- Stian Grytøyr (initial author)
- Scott Donnelly (current maintainer)
Credits
The initial code was largely based on express-jwt.
Contributors
- Foxandxss
- soygul
- tunnckoCore
- getuliojr
- cesarandreu
- michaelwestphal
- Jackong
- danwkennedy
- nfantone
- scttcper
- jhnns
- dunnock
- 3imed-jaberi
License
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/koajs/.github/SECURITY.md:1
- Info: Found linked content: github.com/koajs/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/koajs/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/koajs/.github/SECURITY.md:1
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
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 26 are checked with a SAST tool
Reason
11 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-h452-7996-h45h
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-2j2x-2gpw-g8fm
- Warn: Project is vulnerable to: GHSA-4q6p-r6v2-jvc5
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
Score
3.4
/10
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