connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
Installations
npm install express-jwt
Developer Guide
Typescript
Yes
Module System
CommonJS
Min. Node Version
>= 8.0.0
Node Version
20.16.0
NPM Version
10.8.1
Score
99
Supply Chain
99.5
Quality
84.3
Maintenance
100
Vulnerability
98.6
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (95.15%)
JavaScript (4.85%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
auth0
Download Statistics
Total Downloads
133,694,892
Last Day
16,900
Last Week
484,999
Last Month
1,899,950
Last Year
21,579,705
GitHub Statistics
MIT License
4,495 Stars
324 Commits
443 Forks
155 Watchers
10 Branches
95 Contributors
Updated on Feb 09, 2025
Bundle Size
58.29 kB
Minified
17.25 kB
Minified + Gzipped
Package Meta Information
Latest Version
8.5.1
Package Id
express-jwt@8.5.1
Unpacked Size
27.87 kB
Size
8.76 kB
File Count
9
NPM Version
10.8.1
Node Version
20.16.0
Published on
Dec 09, 2024
Total Downloads
Cumulative downloads
Total Downloads
133,694,892
Last Day
-14.2%
16,900
Compared to previous day
Last Week
-4.7%
484,999
Compared to previous week
Last Month
31.9%
1,899,950
Compared to previous month
Last Year
-13.3%
21,579,705
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
express-jwt
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.
Install
$ npm install express-jwt
API
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 expressRequest
and returns the token, by default it looks in theAuthorization
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 toreq.auth
.- Plus... all the options available in the jsonwebtoken verify function.
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;
Usage
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.
Required Parameters
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});
Additional Options
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"] });
Customizing Token Location
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);
Retrieve key dynamically
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 expressrequest
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);
Secret rotation
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};
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 function(req, payload, done)
:
req
(Object
) - The expressrequest
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);
Handling expired tokens
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 })
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(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);
Typescript
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);
Migration from v6
- The middleware function is now available as a named import rather than a default one: import { expressjwt } from 'express-jwt'
- The decoded JWT payload is now available as req.auth rather than req.user
- The
secret
function had(req, header, payload, cb)
, now it can return a promise and receives(req, token)
.token
hasheader
andpayload
. - The
isRevoked
function had(req, payload, cb)
, now it can return a promise and receives(req, token)
.token
hasheader
andpayload
.
Related Modules
- jsonwebtoken — JSON Web Token sign and verification
- express-jwt-permissions - Permissions middleware for JWT tokens
Tests
$ npm install
$ npm test
Contributors
Check them out here
Issue Reporting
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.
Author
License
This project is licensed under the MIT license. See the LICENSE file for more info.
Stable Version
Stable Version
8.5.1
High
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
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/semgrep.yml:8
- Info: no jobLevel write permissions 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
security policy file detected
Details
- Info: security policy file detected: github.com/auth0/.github/.github/SECURITY.md:1
- Info: Found linked content: github.com/auth0/.github/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/auth0/.github/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/auth0/.github/.github/SECURITY.md:1
Reason
8 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 7
Reason
branch protection is not maximal on development and all release branches
Details
- Info: 'allow deletion' disabled on branch 'master'
- Info: 'force pushes' disabled on branch 'master'
- Warn: 'branch protection settings apply to administrators' is disabled on branch 'master'
- Info: 'stale review dismissal' is required to merge on branch 'master'
- Warn: required approving review count is 1 on branch 'master'
- Warn: codeowners review is not required on branch 'master'
- Info: 'last push approval' is required to merge on branch 'master'
- Warn: no status checks found to merge onto branch 'master'
- Info: PRs are required in order to make changes on branch 'master'
Reason
Found 7/22 approved changesets -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/semgrep.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/auth0/express-jwt/semgrep.yml/master?enable=pin
- Info: 0 out of 1 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 15 are checked with a SAST tool
Score
6.5
/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 MoreOther packages similar to express-jwt
@types/express-jwt
Stub TypeScript definitions entry for express-jwt, which provides its own types definitions
express-jwt-permissions
Express middleware for JWT permissions
express-oauth2-jwt-bearer
Authentication middleware for Express.js that validates JWT bearer access tokens.
express-jwt-authz
Validate a JWTs scope to authorize access to an endpoint