Giter Club home page Giter Club logo

express-oauth2-bearer's Introduction

Please Note: This repository is experimental and will reach end-of-life on June 30, 2023. To protect Express.js APIs with JWT Bearer Tokens, we recommend express-oauth2-jwt-bearer. See the Migration Guide and the blog post for more details).

Authentication middleware for Express.js that validates access tokens following RFC 6750. The purpose of this library is to protect OAuth 2.0 resources.

Table of Contents

FOSSA Status

Installation

This library is installed with npm:

npm i express-oauth2-bearer --save

Getting Started

The library needs the following values to authroize requests:

  • Issuer Base URL: The base URL of the authorization server. If you're using Auth0, this is your tenant Domain pre-pended with https:// (like https://tenant.auth0.com) found on the Settings tab for your Application in the Auth0 dashboard.
  • Allowed Audiences: Audience identifier (or multiple separated by a comma) allowed for the access token. If you're using Auth0, this is the Identifier found on the Settings tab for your API in the Auth0 dashboard.

These can be configured in a .env file in the root of your application:

# .env

ISSUER_BASE_URL=https://YOUR_DOMAIN
ALLOWED_AUDIENCES=https://api.yourapplication.com

... or in your application code:

const { auth } = require('express-oauth2-bearer');

app.use(auth({
  issuerBaseURL: 'https://tenant.auth0.com',
  allowedAudiences: 'https://api.yourapplication.com'
}));

The OpenID strategy is the default strategy for token validation. With the configuration values set in the .env file, the following code will restrict requests to all proceeding routes to ones that have a valid access token with the https://api.yourapplication.com audience and the read:products scope:

const { auth, requiredScopes } = require('express-oauth2-bearer');

app.use(auth());

app.get('/products',
  requiredScopes('read:products'),
  (req, res) => {
    console.dir(req.auth.claims);
    res.sendStatus(200);
  });

If access tokens are not expected to be signed like OpenID Connect ID tokens, add the auth middleware with a callback to validate as follows:

const { auth, requiredScopes } = require('express-oauth2-bearer');

const validateAccesToken = async (token) => {
  const token = await db.tokens.find(token);
  if (token.expired) { return; }
  return token;
};

app.use(auth(validateAcessToken)));

app.get('/products',
  requiredScopes('read:products'),
  (req, res) => {
    console.dir(req.auth.claims);
    res.sendStatus(200);
  });

API Documentation:

auth() accepts an asynchronous function receiving an access token and returning a set of claims.

requiredScopes() accepts either a string or an array of strings.

strategies.openid accepts the following parameters:

Name Default Description
issuerBaseURL env.ISSUER_BASE_URL URL for the token issuer.
allowedAudiences env.ALLOWED_AUDIENCES.split(',') Allowed audiences for the token.
clockTolerance 5 Clock tolerance in seconds for token verification, aka leeway.
clientSecret env.CLIENT_SECRET Client secret, required for tokens signed with symmetric algorithms.

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Contributions can be made to this library through PRs to fix issues, improve documentation or add features. Please fork this repo, create a well-named branch, and submit a PR with a complete template filled out.

Code changes in PRs should be accompanied by tests covering the changed or added functionality. Tests can be run for this library with:

npm install
npm test

When you're ready to push your changes, please run the lint command first:

npm run lint

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.

FOSSA Status

express-oauth2-bearer's People

Contributors

adamjmcgrath avatar damieng avatar dependabot[bot] avatar evansims avatar fossabot avatar jfromaniello avatar jimmyjames avatar joshcanhelp avatar lbalmaceda avatar lzychowski avatar mikemimik avatar notmyself avatar panva avatar snyk-bot avatar sre-57-opslevel[bot] avatar stevehobbsdev avatar widcket avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-oauth2-bearer's Issues

Provide alternative methods of importing keys

Describe the problem you'd like to have solved

Allow for specifying other common key import methods, like X509 using a public key, or PKCS8. The jose package already has support ready for these. The certs could be fetched by making a simple net socket connection, tls upgraded, to the issuer, socket.getPeerCertificate().raw. No dependencies would be added.

Additional thought, in cases of tls, if there is no ISSUER_BASE_URL defined, default to the iss claim value. I believe this would usually be a fqdn of the issuer. Which, if reachable, should have the necessary public key as part of it's TLS cert. I believe this would be the most common use case and would just work out of the box for most folks.

Describe the ideal solution

When setting up the middleware, pass a string that for the desired method in which a key should be imported: i.e. 'jwks' | 'x509' | 'pkcs' , defaulting to jwks.

i.e.

auth({method:'x509'});
// or for simplicity with defaults
auth('x509');

Alternatives and current work-arounds

This package already allows for passing in a public key as a param (I think), or providing a custom getToken handler. However, given the name of the package, I would expect to be able to use other import methods, besides JWKS without having to implement them myself.

Additional information, if any

I'm happy to write this up and submit a PR for review, I just wanted to check with the maintainers for their thoughts and/or blessings, before I do so.

Inline settings are not passed to the openid strategy constructor

Problem: Passing configuration values inline to the auth middleware, the values are not passed into the openid strategy constructor. This causes the library to throw Error: issuerBaseURL is required.

This code:

const handler = auth({
      issuerBaseURL: `https://${domain}`,
      allowedAudiences: audience,
    });

Throws an error at:

throw new Error('issuerBaseURL is required');

This line should pass the params down to the contructor:

params.strategy = openid();

no last version on npm

i'm using npm version 0.4.0 and get error when passing params to auth method. So i checked master branch and params are initialized there

MASTER
index.js

if(!params.strategy) {
    params.strategy = openid(params);
  }

NPM VERSION
index.js

if(!params.strategy) {
    params.strategy = openid() // missing param object;
  }

please renew npm version

Allow for whitelisting certain paths

Describe the problem you'd like to have solved

I have a situation using express router where I want the GET commands of say 3 out of 20 endpoints to not check the access token. Currently there doesn't seem to be this sort of white list feature

Describe the ideal solution

I could pass a list of "public" paths that will be ignored by the authentication header check.

Alternatives and current work-arounds

Add the express-oauth2-bearer library once for each router

Web Socket Support

Checklist

  • I have looked into the Readme and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

Problem:
WebSocket connections are becoming increasingly important in modern web applications, particularly for real-time communication. Currently, the express-oauth2-bearer library is designed primarily for validating OAuth 2.0 access tokens in Express.js HTTP routes. However, it lacks support for WebSocket connections.

Use Case:
Modern web applications often require both HTTP and WebSocket protocols for various functionalities. Integrating OAuth 2.0 authentication seamlessly with WebSocket connections would simplify the authentication process for applications that use both protocols.

Describe the ideal solution

Ideal Solution:
The ideal solution is to extend the functionality of the express-oauth2-bearer library to support WebSocket middleware. This extension should provide a similar level of ease and security for OAuth 2.0 authentication in WebSocket connections as it currently does for HTTP routes. It should include middleware for WebSocket handshake validation and token decoding.

Alternatives and current workarounds

Alternatives and Workarounds:
Currently, users have to manually handle token validation and decoding for WebSocket connections, as the express-oauth2-bearer library is primarily designed for HTTP routes. While this manual approach works, it is less convenient and maintainable than having built-in support within the library. An alternative would be to use separate OAuth 2.0 authentication solutions for WebSocket connections, which can lead to duplicated code and increased complexity.

Additional context

WebSocket connections and HTTP requests have different characteristics, so implementing WebSocket support within the library might require adjustments or new APIs to handle WebSocket authentication seamlessly.
This feature request aims to enhance the library's versatility and usefulness in modern web application development, where a unified authentication approach across different protocols can simplify development and improve security.
Providing support for WebSocket middleware would align with the evolving needs of web applications that increasingly rely on real-time features and OAuth 2.0 authentication.
Is this feature request related to a problem? Please describe.

Yes, this feature request is related to the need for consistent and secure OAuth 2.0 authentication across both HTTP and WebSocket connections in modern web applications.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.