What is express-oauth2-jwt-bearer?
The express-oauth2-jwt-bearer package is designed to help developers implement OAuth 2.0 JWT Bearer Token authentication in their Express.js applications. It simplifies the process of validating JWTs and securing API endpoints.
What are express-oauth2-jwt-bearer's main functionalities?
JWT Validation
This feature allows you to validate JWTs in your Express.js application. The `auth` function from the package is used to create a middleware that checks the validity of the JWT. If the token is valid, the request proceeds to the next middleware or route handler.
const { auth } = require('express-oauth2-jwt-bearer');
const express = require('express');
const app = express();
const checkJwt = auth({
audience: 'YOUR_API_IDENTIFIER',
issuerBaseURL: 'https://YOUR_DOMAIN'
});
app.get('/api/private', checkJwt, (req, res) => {
res.send('This is a private endpoint');
});
app.listen(3000, () => console.log('Server running on port 3000'));
Custom Token Validation
This feature allows you to add custom validation for specific scopes in the JWT. The `requiredScopes` function is used to create a middleware that checks if the JWT contains the required scopes. This is useful for implementing fine-grained access control in your API.
const { auth, requiredScopes } = require('express-oauth2-jwt-bearer');
const express = require('express');
const app = express();
const checkJwt = auth({
audience: 'YOUR_API_IDENTIFIER',
issuerBaseURL: 'https://YOUR_DOMAIN'
});
const checkScopes = requiredScopes('read:messages');
app.get('/api/private-scoped', checkJwt, checkScopes, (req, res) => {
res.send('This is a private endpoint with scope validation');
});
app.listen(3000, () => console.log('Server running on port 3000'));
Other packages similar to express-oauth2-jwt-bearer
express-jwt
The express-jwt package is another popular library for validating JWTs in Express.js applications. It provides similar functionality to express-oauth2-jwt-bearer, allowing you to create middleware for JWT validation. However, express-jwt does not include built-in support for OAuth 2.0 specific features like audience and issuer validation.
passport-jwt
The passport-jwt package is a Passport.js strategy for authenticating with a JSON Web Token. It is used in conjunction with Passport.js, a popular authentication middleware for Node.js. While it provides robust JWT validation, it requires additional setup with Passport.js and does not offer the same level of integration with OAuth 2.0 as express-oauth2-jwt-bearer.
jsonwebtoken
The jsonwebtoken package is a general-purpose library for working with JSON Web Tokens. It allows you to sign, verify, and decode JWTs. While it provides the core functionality needed for JWT handling, it does not offer middleware for Express.js or built-in support for OAuth 2.0 features, making it less convenient for use in Express.js applications compared to express-oauth2-jwt-bearer.
express-oauth2-jwt-bearer (Beta)
Authentication middleware for Express.js that validates JWT Bearer Access Tokens.
Note: This library is currently in Beta status and has not had a complete security review. We do not recommend using this library in production yet. As we move towards general availability, please be aware that releases may contain breaking changes. We will be monitoring the Issues queue here for feedback and questions. PRs and comments on existing PRs are welcome!
Install
This package supports Node ^12.19.0 || ^14.15.0
npm install express-oauth2-jwt-bearer
Getting started
The library requires issuerBaseURL and audience, which can be configured with environmental variables:
ISSUER_BASE_URL=https://YOUR_ISSUER_DOMAIN
AUDIENCE=https://my-api.com
const { auth } = require('express-oauth2-jwt-bearer');
app.use(auth());
... or in the library initialization:
const { auth } = require('express-oauth2-jwt-bearer');
app.use(
auth({
issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN',
audience: 'https://my-api.com'
})
);
... or for JWTs signed with symmetric algorithms (eg HS256
)
const { auth } = require('express-oauth2-jwt-bearer');
app.use(
auth({
issuer: 'https://YOUR_ISSUER_DOMAIN',
audience: 'https://my-api.com',
secret: 'YOUR SECRET',
tokenSigningAlg: 'HS256'
})
);
With this basic configuration, your api will require a valid Access Token JWT bearer token for all routes.
API Documentation
- auth - Middleware that will return a 401 if a valid Access token JWT bearer token is not provided in the request.
- requiredScopes - Check a token's scope claim to include a number of given scopes, raises a 403
insufficient_scope
error if the value of the scope claim does not include all the given scopes. - claimEquals - Check a token's claim to be equal a given JSONPrimitive (string, number, boolean or null) raises a 401
invalid_token
error if the value of the claim does not match. - claimIncludes - Check a token's claim to include a number of given JSONPrimitives (string, number, boolean or null) raises a 401
invalid_token
error if the value of the claim does not include all the given values. - claimCheck - Check the token's claims using a custom method that receives the JWT Payload and should return
true
if the token is valid. Raises a 401 invalid_token
error if the function returns false
.
Examples
const {
auth,
requiredScopes,
claimEquals,
claimIncludes,
claimCheck
} = require('express-oauth2-jwt-bearer');
app.use(auth());
app.get('/api/messages',
requiredScopes('read:msg', 'write:msg'),
(req, res, next) => {
}
);
app.get('/api/admin', claimEquals('isAdmin', true), (req, res, next) => {
});
app.get('/api/admin/managers',
claimIncludes('role', 'admin', 'manager'),
(req, res, next) => {
}
);
app.get('/api/admin/edit',
claimCheck(({ isAdmin, roles }) => isAdmin && roles.includes('editor')),
(req, res, next) => {
}
);
Along with the other security best practices in the Express.js documentation, we recommend you use helmet in addition to this middleware which can help protect your app from some well-known web vulnerabilities by setting default security HTTP headers.
Error Handling
This SDK raises errors with err.status
and err.headers
according to rfc6750. The Express.js default error handler will set the error response with:
res.statusCode
set from err.status
res.statusMessage
set according to the status code.- The body will be the HTML of the status code message when in production environment, otherwise will be
err.stack
. - Any headers specified in an
err.headers
object.
The error_description
in the WWW-Authenticate
header will contain useful information about the error, which you may not want to disclose in Production.
See the Express.js docs on error handling for more information on writing custom error handlers.
Troubleshooting
Getting Error: Cannot find module 'jose-node-cjs-runtime/jwks/remote'
when I run the SDK
This package takes a dependency on jose which uses package exports which requires Node ^12.19.0 || ^14.15.0
.
Even if you are using the correct version of Node, you may still run into this in some tooling that does not yet support package exports, like jest or Webpack 4.
To workaround this issue in jest, see how we use a custom resolver for this project.
Contributing
See monorepo's contributing guidelines.
Support + Feedback
Please use the Issues queue in this repo for questions and feedback.
Vulnerability Reporting
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
What is Auth0?
Auth0 helps you to easily:
- implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
- log in users with username/password databases, passwordless, or multi-factor authentication
- link multiple user accounts together
- generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
- access demographics and analytics detailing how, when, and where users are logging in
- enrich user profiles from other data sources using customizable JavaScript rules
Why Auth0?
License
This project is licensed under the MIT license. See the LICENSE file for more info.