Gathering detailed insights and metrics for koa-jwt2
Gathering detailed insights and metrics for koa-jwt2
npm install koa-jwt2
Typescript
Module System
Min. Node Version
Node Version
NPM Version
72
Supply Chain
99.5
Quality
73.1
Maintenance
50
Vulnerability
97.9
License
JavaScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
1,314,190
Last Day
827
Last Week
6,171
Last Month
24,390
Last Year
304,540
MIT License
14 Stars
7 Commits
3 Watchers
1 Branches
1 Contributors
Updated on Jul 27, 2023
Minified
Minified + Gzipped
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
Cumulative downloads
Total Downloads
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
4
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.
$ npm install koa-jwt2 --save
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);
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 koa ctx
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});
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 koa context
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);
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);
$ npm install
$ npm test
Check them out here
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
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
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Score
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