Installations
npm install koa-jwt2
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>= 8.0.0
Node Version
8.9.0
NPM Version
5.6.0
Score
72
Supply Chain
99.5
Quality
73.1
Maintenance
50
Vulnerability
97.9
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
okoala
Download Statistics
Total Downloads
1,314,190
Last Day
827
Last Week
6,171
Last Month
24,390
Last Year
304,540
GitHub Statistics
MIT License
14 Stars
7 Commits
3 Watchers
1 Branches
1 Contributors
Updated on Jul 27, 2023
Bundle Size
60.50 kB
Minified
18.12 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.3
Package Id
koa-jwt2@1.0.3
Unpacked Size
29.12 kB
Size
7.58 kB
File Count
12
NPM Version
5.6.0
Node Version
8.9.0
Total Downloads
Cumulative downloads
Total Downloads
1,314,190
Last Day
0.9%
827
Compared to previous day
Last Week
2.7%
6,171
Compared to previous week
Last Month
-1.4%
24,390
Compared to previous month
Last Year
0.7%
304,540
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
4
koa-jwt2
Koa middleware that validates JsonWebTokens and sets ctx.state.user
.
This module lets you authenticate HTTP requests using JWT tokens in your Node.js applications. JWTs are typically used to protect API endpoints, and are often issued using OpenID Connect.
Install
$ npm install koa-jwt2 --save
Usage
The JWT authentication middleware authenticates callers using a JWT.
If the token is valid, ctx.state.user
will be set with the JSON object decoded
to be used by later middleware for authorization and access control.
For example,
1var jwt = require("koa-jwt2"); 2 3app.get("/protected", jwt({ secret: "shhhhhhared-secret" }), async function( 4 ctx 5) { 6 if (!ctx.state.user.admin) return (ctx.status = 401); 7 ctx.status = 200; 8});
You can specify audience and/or issuer as well:
1jwt({ 2 secret: "shhhhhhared-secret", 3 audience: "http://myapi/protected", 4 issuer: "http://issuer" 5});
If the JWT has an expiration (
exp
), it will be checked.
If you are using a base64 URL-encoded secret, pass a Buffer
with base64
encoding as the secret instead of a string:
1jwt({ secret: new Buffer("shhhhhhared-secret", "base64") });
Optionally you can make some paths unprotected as follows:
1app.use(jwt({ secret: "shhhhhhared-secret" }).unless({ path: ["/token"] }));
This is especially useful when applying to multiple routes. In the example above, path
can be a string, a regexp, or an array of any of those.
For more details on the
.unless
syntax including additional options, please see koa-unless.
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"); 2jwt({ secret: publicKey });
By default, the decoded token is attached to ctx.state.user
but can be configured with the property
option.
1jwt({ secret: publicKey, property: "auth" });
A custom function for extracting the token from a request can be specified with
the getToken
option. This is useful if you need to pass the token through a
query parameter or a cookie. You can throw an error in this function and it will
be handled by koa-jwt2
.
1app.use( 2 jwt({ 3 secret: "hello world !", 4 credentialsRequired: false, 5 getToken: function fromHeaderOrQuerystring(ctx) { 6 if ( 7 ctx.headers.authorization && 8 ctx.headers.authorization.split(" ")[0] === "Bearer" 9 ) { 10 return ctx.headers.authorization.split(" ")[1]; 11 } else if (ctx.query && ctx.query.token) { 12 return ctx.query.token; 13 } 14 return null; 15 } 16 }) 17);
Multi-tenancy
If you are developing an application in which the secret used to sign tokens is not static, you can provide a async function as the secret
parameter. The function has the signature: async function(ctx, payload)
:
ctx
(Object
) - The koactx
object.payload
(Object
) - An object with the JWT claims.
need to return a secret string or promise to use to verify the JWT.
For example, if the secret varies based on the JWT issuer:
1const jwt = require("koa-jwt2"); 2const data = require("./data"); 3const utilities = require("./utilities"); 4 5const secretAsync = async function(ctx, payload) { 6 const issuer = payload.iss; 7 8 return new Promise((resolve, reject) => { 9 data.getTenantByIdentifier(issuer, function(err, tenant) { 10 if (err) { 11 return reject(err); 12 } 13 if (!tenant) { 14 reject(new Error("missing_secret")); 15 } 16 17 const secret = utilities.decrypt(tenant.secret); 18 resolve(secret); 19 }); 20 }); 21}; 22 23app.get("/protected", jwt({ secret: secretCallback }), async function(ctx) { 24 if (!ctx.state.user.admin) { 25 ctx.throw(401); 26 } 27 ctx.status = 200; 28 ctx.body = ""; 29});
Revoked tokens
It is possible that some tokens will need to be revoked so they cannot be used any longer. You can provide a function as the isRevoked
option. The signature of the function is async function(ctx, payload)
:
ctx
(Object
) - The koacontext
object.payload
(Object
) - An object with the JWT claims.
For example, if the (iss, jti)
claim pair is used to identify a JWT:
1const jwt = require("koa-jwt2"); 2const data = require("./data"); 3const utilities = require("./utilities"); 4 5const isRevokedAsync = function(req, payload, done) { 6 const issuer = payload.iss; 7 const tokenId = payload.jti; 8 9 return new Promise((resolve, reject) => { 10 data.getRevokedToken(issuer, tokenId, function(err, token) { 11 if (err) { 12 return reject(err); 13 } 14 resolve(!!token); 15 }); 16 }); 17}; 18 19app.get( 20 "/protected", 21 jwt({ 22 secret: "shhhhhhared-secret", 23 isRevoked: isRevokedAsync 24 }), 25 async function(ctx) { 26 if (!ctx.state.user.admin) { 27 ctx.throw(401); 28 } 29 ctx.status = 200; 30 ctx.body = ""; 31 } 32);
Error handling
The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:
1app.use(async function(ctx, next) { 2 try { 3 await next(); 4 } catch (err) { 5 if (err.name === "UnauthorizedError") { 6 ctx.status = 401; 7 ctx.body = "invalid token..."; 8 } 9 } 10});
You might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option credentialsRequired:
1app.use( 2 jwt({ 3 secret: "hello world !", 4 credentialsRequired: false 5 }) 6);
Related Modules
- jsonwebtoken — JSON Web Token sign and verification
Tests
$ npm install
$ npm test
Contributors
Check them out here
License
This project is licensed under the MIT license. See the LICENSE file for more info.

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/7 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
- Warn: no pull requests merged into dev branch
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Score
3
/10
Last Scanned on 2025-02-10
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