Gathering detailed insights and metrics for express-jwt
Gathering detailed insights and metrics for express-jwt
Gathering detailed insights and metrics for express-jwt
Gathering detailed insights and metrics for express-jwt
express-jwt-blacklist
express-jwt plugin for token blacklisting
middy-middleware-jwt-auth
A middy JSON web token authorization middleware inspired by express-jwt.
express-jwt-jwks
Simple JWT auth using JWKS key sets for Express. Wraps express-jwt and jwks-rsa. AWS Cognito compatible.
express-jwt-authz
Validate a JWTs scope to authorize access to an endpoint
connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
npm install express-jwt
98.6
Supply Chain
99.5
Quality
83.2
Maintenance
100
Vulnerability
98.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
4,495 Stars
316 Commits
443 Forks
154 Watching
9 Branches
69 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
TypeScript (95.15%)
JavaScript (4.85%)
Cumulative downloads
Total Downloads
Last day
-10.5%
90,465
Compared to previous day
Last week
3.6%
483,354
Compared to previous week
Last month
13.8%
1,953,997
Compared to previous month
Last year
-19.3%
21,812,970
Compared to previous year
This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.
$ npm install express-jwt
expressjwt(options)
Options has the following parameters:
secret: jwt.Secret | GetVerificationKey
(required): The secret as a string or a function to retrieve the secret.getToken?: TokenGetter
(optional): A function that receives the express Request
and returns the token, by default it looks in the Authorization
header.isRevoked?: IsRevoked
(optional): A function to verify if a token is revoked.onExpired?: ExpirationHandler
(optional): A function to handle expired tokens.credentialsRequired?: boolean
(optional): If its false, continue to the next middleware if the request does not contain a token instead of failing, defaults to true.requestProperty?: string
(optional): Name of the property in the request object where the payload is set. Default to req.auth
.The available functions have the following interface:
GetVerificationKey = (req: express.Request, token: jwt.Jwt | undefined) => Promise<jwt.Secret>;
IsRevoked = (req: express.Request, token: jwt.Jwt | undefined) => Promise<boolean>;
TokenGetter = (req: express.Request) => string | Promise<string> | undefined;
Basic usage using an HS256 secret:
1var { expressjwt: jwt } = require("express-jwt"); 2// or ES6 3// import { expressjwt, ExpressJwtRequest } from "express-jwt"; 4 5app.get( 6 "/protected", 7 jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }), 8 function (req, res) { 9 if (!req.auth.admin) return res.sendStatus(401); 10 res.sendStatus(200); 11 } 12);
The decoded JWT payload is available on the request via the auth
property.
The default behavior of the module is to extract the JWT from the
Authorization
header as an OAuth2 Bearer token.
The algorithms
parameter is required to prevent potential downgrade attacks when providing third party libraries as secrets.
:warning: Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.
1jwt({ 2 secret: "shhhhhhared-secret", 3 algorithms: ["HS256"], 4 //algorithms: ['RS256'] 5});
You can specify audience and/or issuer as well, which is highly recommended for security purposes:
1jwt({ 2 secret: "shhhhhhared-secret", 3 audience: "http://myapi/protected", 4 issuer: "http://issuer", 5 algorithms: ["HS256"], 6});
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({ 2 secret: Buffer.from("shhhhhhared-secret", "base64"), 3 algorithms: ["RS256"], 4});
To only protect specific paths (e.g. beginning with /api
), use express router call use
, like so:
1app.use("/api", jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }));
Or, the other way around, if you want to make some paths unprotected, call unless
like so.
1app.use( 2 jwt({ 3 secret: "shhhhhhared-secret", 4 algorithms: ["HS256"], 5 }).unless({ path: ["/token"] }) 6);
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 express-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, algorithms: ["RS256"] });
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 express-jwt
.
1app.use( 2 jwt({ 3 secret: "hello world !", 4 algorithms: ["HS256"], 5 credentialsRequired: false, 6 getToken: function fromHeaderOrQuerystring(req) { 7 if ( 8 req.headers.authorization && 9 req.headers.authorization.split(" ")[0] === "Bearer" 10 ) { 11 return req.headers.authorization.split(" ")[1]; 12 } else if (req.query && req.query.token) { 13 return req.query.token; 14 } 15 return null; 16 }, 17 }) 18);
If you need to obtain the key dynamically from other sources, you can pass a function in the secret
parameter with the following parameters:
req
(Object
) - The express request
object.token
(Object
) - An object with the JWT payload and headers.For example, if the secret varies based on the issuer:
1var jwt = require("express-jwt"); 2var data = require("./data"); 3var utilities = require("./utilities"); 4 5var getSecret = async function (req, token) { 6 const issuer = token.payload.iss; 7 const tenant = await data.getTenantByIdentifier(issuer); 8 if (!tenant) { 9 throw new Error("missing_secret"); 10 } 11 return utilities.decrypt(tenant.secret); 12}; 13 14app.get( 15 "/protected", 16 jwt({ secret: getSecret, algorithms: ["HS256"] }), 17 function (req, res) { 18 if (!req.auth.admin) return res.sendStatus(401); 19 res.sendStatus(200); 20 } 21);
The getSecret callback could also be used in cases where the same issuer might issue tokens with different keys at certain point:
1var getSecret = async function (req, token) { 2 const { iss } = token.payload; 3 const { kid } = token.header; 4 // get the verification key by a given key-id and issuer. 5 return verificationKey; 6};
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 function(req, payload, done)
:
req
(Object
) - The express request
object.token
(Object
) - An object with the JWT payload and headers.For example, if the (iss, jti)
claim pair is used to identify a JWT:
1const jwt = require("express-jwt"); 2const data = require("./data"); 3 4const isRevokedCallback = async (req, token) => { 5 const issuer = token.payload.iss; 6 const tokenId = token.payload.jti; 7 const token = await data.getRevokedToken(issuer, tokenId); 8 return token !== "undefined"; 9}; 10 11app.get( 12 "/protected", 13 jwt({ 14 secret: "shhhhhhared-secret", 15 algorithms: ["HS256"], 16 isRevoked: isRevokedCallback, 17 }), 18 function (req, res) { 19 if (!req.auth.admin) return res.sendStatus(401); 20 res.sendStatus(200); 21 } 22);
You can handle expired tokens as follows:
1 jwt({ 2 secret: "shhhhhhared-secret", 3 algorithms: ["HS256"], 4 onExpired: async (req, err) => { 5 if (new Date() - err.inner.expiredAt < 5000) { return;} 6 throw err; 7 },, 8 })
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(function (err, req, res, next) { 2 if (err.name === "UnauthorizedError") { 3 res.status(401).send("invalid token..."); 4 } else { 5 next(err); 6 } 7});
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 algorithms: ["HS256"], 5 credentialsRequired: false, 6 }) 7);
A Request
type is provided from express-jwt
, which extends express.Request
with the auth
property. It could be aliased, like how JWTRequest
is below.
1import { expressjwt, Request as JWTRequest } from "express-jwt"; 2 3app.get( 4 "/protected", 5 expressjwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }), 6 function (req: JWTRequest, res: express.Response) { 7 if (!req.auth?.admin) return res.sendStatus(401); 8 res.sendStatus(200); 9 } 10);
secret
function had (req, header, payload, cb)
, now it can return a promise and receives (req, token)
. token
has header
and payload
.isRevoked
function had (req, payload, cb)
, now it can return a promise and receives (req, token)
. token
has header
and payload
.$ npm install
$ npm test
Check them out here
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.
The latest stable version of the package.
Stable Version
1
7.7/10
Summary
Authorization bypass in express-jwt
Affected Versions
<= 5.3.3
Patched Versions
6.0.0
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
branch protection is not maximal on development and all release branches
Details
Reason
Found 6/27 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
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