Git Product home page Git Product logo

node-oauth2-jwt-bearer's Introduction

oauth2-jwt-bearer

Monorepo for oauth2-jwt-bearer. Contains the following packages:

package published description
oauth2-bearer Gets Bearer tokens from a request and issues errors per rfc6750
access-token-jwt Verfies and decodes Access Token JWTs loosley following draft-ietf-oauth-access-token-jwt-12
express-oauth2-jwt-bearer Authentication middleware for Express.js that validates JWT Bearer Access Tokens

Feedback

Contributing

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

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

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 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

node-oauth2-jwt-bearer's People

Contributors

adamjmcgrath avatar danielkucal avatar dependabot[bot] avatar evansims avatar ewanharris avatar frederikprijck avatar indeed404 avatar lbalmaceda avatar panva avatar robintail 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-oauth2-jwt-bearer's Issues

[docs] 404 error in the GitHub Pages documentation when clicking on a class or an interface

Checklist

  • I have looked into the Readme and Examples, 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.

Description

Hello,

Clicking on any classes or interfaces in the documentation hosted at https://auth0.github.io/node-oauth2-jwt-bearer/ results in a 404 error. I cloned the repo and built the doc locally and the links work, so maybe the hosted version is outdated ?

Reproduction

  1. Go to https://auth0.github.io/node-oauth2-jwt-bearer/
  2. Click to any of the links in the Classes or Interfaces section (e.g. InsufficientScopeError)
  3. Get a 404 error from GitHub pages.

Additional context

No response

express-oauth2-jwt-bearer version

Node.js version

Unable to recovery from temporarily unavailable discovery document

Description

auth handler from package express-oauth2-jwt-bearer is unable to recover in case OpenID discovery document cannot be read.

It should not cache errors forever.

Reproduction

Detail the steps taken to reproduce this error, what was expected, and whether this issue can be reproduced consistently or if it is intermittent.

Where applicable, please include:

  • Code sample to reproduce the issue

Code is basically as in https://github.com/auth0/node-oauth2-jwt-bearer/tree/main/packages/express-oauth2-jwt-bearer#library-initialization

import { auth } from 'express-oauth2-jwt-bearer';

const accessTokenEnforcingHandler = auth({
  issuerBaseURL: process.env.AUTH_SERVICE_DISCOVERY_URI,
  audience: 'whatever'
});
app.use(accessTokenEnforcingHandler)

The code in

discovery || discover(issuerBaseURL, { agent, timeoutDuration });
always caches the request to get the discovery document regardless of its outcome. This means in case of a temporary network error or similar hickups, the erroneous promise will be stored in the variable discovery and the Express handler accessTokenEnforcingHandler will reject every token forever.

This can be seen if the discovery document is unavailable at the time the handler is first used to validate a token.

Potential fix: Clear the variable discovery in case the promise stored in discovery resolves to an error.

Environment

Please provide the following:

  • Version of this library used: 1.3.0
  • Version of the platform or framework used, if applicable:
  • Other relevant versions (language, server software, OS, browser):
  • Other modules/plugins/libraries that might be involved:

Support: Implementation with NEstJS functional?

Description

Hi there, just a support question:

I've been trying to implement auth0 to use for our NestJs app.

I followed your tutorial on youtube: https://www.youtube.com/watch?v=JzndSOAb6SQ
But this video uses not this actual package, but the other ones that were previously in place (express-jwt, express-jwt-authz, and jwks-rsa)

I'm just curious to know if this new one is easily implementable for a NestJs app as well?
and How different should it be done?

publicKey without discovery

Checklist

  • I have looked into the Readme and Examples, 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

It seems possible to avoid discovery altogether by specifying issuer instead of issuerBaseURL, and this is perfectly fine with symmetrical algorithms. However, it seems impossible to provide an asymmetrical algorithm and not specify issuerBaseURL.

Describe the ideal solution

I would like to pass the public key explicitly without doing discovery. So something like defining issuer, audience, and then public key in secret. The library jose seems to allow passing the public key already, but we never get here because node-oauth2-jwt-bearer will throw before that during validation.

Alternatives and current workarounds

Currently not possible.

Additional context

No response

Add support for node 18

Describe the problem you'd like to have solved

In my project I use node v18.8.0, however I get the following error:
error [email protected]: The engine "node" is incompatible with this module. Expected version "12.19.0 || ^14.15.0 || ^16.13.0". Got "18.8.0"

Any chance you would add support for the node 18 any time soon?
Thank you

Is it possible to use this with JWE encrypted access token?

Checklist

  • I have looked into the Readme and Examples, 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

I'm trying to use this library with my OpenIddict Auth server - which issues encrypted tokens.

Describe the ideal solution

I'd like a straightforward, documented way to decrypt and use these tokens for protecting my resource server.

Alternatives and current workarounds

No response

Additional context

No response

InvalidTokenError: Failed to fetch authorization server metadata

Checklist

  • I have looked into the Readme and Examples, 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.

Description

Been using this library to validate the access tokens and recently started to get a 401 error saying Failed to fetch authorization server metadata.

As I started to dig into the library code, found out that the discovery method is failing to fetch the openid and oauth configs.

Note: I have verified my issuer url and seems to be good.

Pasting the error being thrown inside the catch block of the discover method:

AggregateError: 
    at internalConnectMultiple (node:net:1114:18)
    at internalConnectMultiple (node:net:1177:5)
    at Timeout.internalConnectMultipleTimeout (node:net:1687:3)
    at listOnTimeout (node:internal/timers:575:11)
    at processTimers (node:internal/timers:514:7) {
  code: 'ETIMEDOUT',
  [errors]: [
    Error: connect ETIMEDOUT 104.19.167.24:443
        at createConnectionError (node:net:1634:14)
        at Timeout.internalConnectMultipleTimeout (node:net:1685:38)
        at listOnTimeout (node:internal/timers:575:11)
        at processTimers (node:internal/timers:514:7) {
      errno: -110,
      code: 'ETIMEDOUT',
      syscall: 'connect',
      address: '104.19.167.24',
      port: 443
    },
    Error: connect ENETUNREACH 2606:4700::6813:a718:443 - Local (:::0)
        at internalConnectMultiple (node:net:1176:40)
        at Timeout.internalConnectMultipleTimeout (node:net:1687:3)
        at listOnTimeout (node:internal/timers:575:11)
        at processTimers (node:internal/timers:514:7) {
      errno: -101,
      code: 'ENETUNREACH',
      syscall: 'connect',
      address: '2606:4700::6813:a718',
      port: 443
    },
    Error: connect ETIMEDOUT 104.19.168.24:443
        at createConnectionError (node:net:1634:14)
        at Timeout.internalConnectMultipleTimeout (node:net:1685:38)
        at listOnTimeout (node:internal/timers:575:11)
        at processTimers (node:internal/timers:514:7) {
      errno: -110,
      code: 'ETIMEDOUT',
      syscall: 'connect',
      address: '104.19.168.24',
      port: 443
    },
    Error: connect ENETUNREACH 2606:4700::6813:a818:443 - Local (:::0)
        at internalConnectMultiple (node:net:1176:40)
        at Timeout.internalConnectMultipleTimeout (node:net:1687:3)
        at listOnTimeout (node:internal/timers:575:11)
        at processTimers (node:internal/timers:514:7) {
      errno: -101,
      code: 'ENETUNREACH',
      syscall: 'connect',
      address: '2606:4700::6813:a818',
      port: 443
    }
  ]
}

Assuming the time out (5000 ms) specified inside the fetch method is causing to fail and throw. Because when I have tried to fetch the openid configs using curl with the specific url https://{issuer_base_url}/.well-known/openid-configuration, I was able to get the configs.

Reproduction

  1. Generate an auth0 access token and append to the authorization header of the request: authorization: Bearer access_token.
  2. Use the express-oauth2-jwt-bearer library to validate the token.
import { auth as auth0 } from 'express-oauth2-jwt-bearer';
import { promisify } from 'util';

async validateAuth0Token(req: Request, res: Response) {
    const validateToken = promisify(
      auth0({
        issuerBaseURL: ISSUER_BASE_URL,
        audience: AUDIENCE,
        tokenSigningAlg: 'RS256',
      }),
    );

    await validateToken(req, res);
  }

Additional context

No response

express-oauth2-jwt-bearer version

1.6.0

Node.js version

20.10.0

Add an additional agnostic and lightweight solution to build on top

Describe the problem you'd like to have solved

I have successfully implemented express-oauth2-jwt-bearer in a Next.js app using API Routes.

I run into some incompatibility issues but I managed to solve them. For instance, express-oauth2-jwt-bearer uses req.is() here, but it is not available in Next.js API Routes. This made me implement workarounds.

Another thing that I have noticed is the size of the package. Why is this package bloated? Here is what bundlephobia.com reports. And this (see screenshot below) is what the Import Cost VSCode Extension reports when importing auth.

Screenshot 2022-09-01 at 12 02 21

I guess most of the code comes from jose. But, can we reduce it even more? I'm thinking on tree shaking. This could have a huge impact on serverless environments. ⚡️

Describe the ideal solution

It would be awesome if you guys could ship an agnostic and lightweight solution. I'm thinking of a low-level solution, so other developers can build on top of it to satisfy their needs or create more integrations with their preferred Node.js frameworks (while the official is not ready yet).

Alternatives and current work-arounds

Publishing access-token-jwt and oauth2-bearer could help.

Documentation for auth() results in Express error.

Description

In the file node-oauth2-jwt-bearer/packages/express-oauth2-jwt-bearer/src/index.ts, the documentation for auth() includes a description of how to add the AuthOptions but the example results in an error from Express: TypeError: app.use() requires a middleware function.

From the Documentation:

app.use({
  issuerBaseURL: 'http://issuer.example.com',
  audience: 'https://myapi.com'
});

Working Code:

app.use(auth({
  issuerBaseURL: 'http://issuer.example.com',
  audience: 'https://myapi.com'
}));

or more like the Auth0 01-authorization-rs256

const checkJwt = auth({
  issuerBaseURL: 'http://issuer.example.com',
  audience: 'https://myapi.com'
});

app.use(checkJwt);
// or
app.get('/protected', checkJwt, (res, req) => {});

Reproduction

Complete code sample to reproduce error:

// server.js
import express from 'express';
import { auth } from 'express-oauth2-jwt-bearer';

const app = express();

// middleware example from documentation
app.use({
  issuerBaseURL: 'http://issuer.example.com',
  audience: 'https://myapi.com'
});

// results in TypeError: app.use() requires a middleware function

....

Environment

node: v16.14.0
express: ^v4.17.1
express-oauth2-jwt-bearer: ^1.1.0

[express-oauth2-jwt-bearer] What is the best practice to allow request to go through despite token being unauthorized?

I'm migrating to express-oauth2-jwt-bearer and trying to fit into my existing project authentication & authorization pipeline.

I would like to have auth() try to authenticate, but still let the user through in an unauthenticated state. Currently, the middleware calls next with the error if unauthorized, which by default goes to the Express error handling middleware and returns a 401 response.

I could add a second step in the pipeline just to catch that possible error, but then that error middleware would also catch any other kind of error and would get in the way of my standard error pipeline.

I am used to passport and this the way I would handle it before:

passport.authenticate('jwt', function(err, user, info) {
  // here I would do whatever in case of invalid token, letting user through

Unble to add the express package on node 17

Hello,

I tried to install the package with the command yarn add express-oauth2-jwt-bearer

but I got this error

The engine "node" is incompatible with this module. Expected version "12.19.0 || ^14.15.0 || ^16.13.0". Got "17.4.0"

I know it's related to my node js version, but I need node 17 for other packages. Instead of checking a specific version, could the package be installed on a version greater than node 12?

Node js is updated very often and I will keep it up to date, so this is a problem.

Thank you.

Fetching subject from JWT?

Description

I'm trying to get the sub after JWT validation, following the sample code in the introductory blogpost, but I'm hitting an error:

TypeError: Cannot read properties of undefined (reading 'payload')
    at $PROJECT_ROOT/index.js:9:41
    at Layer.handle [as handle_request] ($PROJECT_ROOT/node_modules/express/lib/router/layer.js:95:5)
    at next ($PROJECT_ROOT/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch ($PROJECT_ROOT/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] ($PROJECT_ROOT/node_modules/express/lib/router/layer.js:95:5)
    at $PROJECT_ROOT/node_modules/express/lib/router/index.js:284:15
    at Function.process_params ($PROJECT_ROOT/node_modules/express/lib/router/index.js:346:12)
    at next ($PROJECT_ROOT/node_modules/express/lib/router/index.js:280:10)
    at $PROJECT_ROOT/node_modules/express-oauth2-jwt-bearer/dist/index.js:355:13

Reproduction

Sample package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "express-oauth2-jwt-bearer": "^1.1.0"
  }
}

Set-up

  • Save sample code as index.js
  • Create .env file as per blogpost with ISSUER_BASE_URL and AUDIENCE defined.

#### Running

nvm use 16
npm install
node index.js
  • If I remove the reference to res.auth (e.g. making the response message just Hello!), I don't hit an error.
  • I'm testing with a Bearer token that I received from an SPA hitting Auth0 directly. I can see a valid exchange in the Logs on the dashboard.
  • If I manually put the token through echo ... | base64 --decode the signature and body look fine & I can see the subject/aud/scopes etc.

Environment

Please provide the following:

  • Version of this library used: 1.1.0
  • Version of the platform or framework used, if applicable: Node 16.15.0
  • Other relevant versions (language, server software, OS, browser): macOS 12 (monterey)
  • Other modules/plugins/libraries that might be involved: dotenv (16.0.1), express (4.18.1)

Please let me know if I can give any other details.

access-token-jwt missing in dependencies

Description

access-token-jwt dependency is missing from express-oauth2-jwt-bearer package

Reproduction

  • npm install --save express-oauth2-jwt-bearer
  • Require express-oauth2-jwt-bearer package in your app
  • Try to build

You will get build errors with:
Cannot find module 'access-token-jwt' or its corresponding type declarations.

Support checking permissions instead of scope

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

Like you folks did in the express-jwt-authz library, I need the ability to check the permissions of a jwt instead of the scopes.

Describe the ideal solution

'requiredScopes' should work similar to express-jwt-authz where I can simply switch to check against the jwt permissions.

Alternatives and current work-arounds

Only workaround (that I can't get to work lately) is https://github.com/auth0/express-jwt-authz

Additional context

None

auth middleware expects credentials for CORS-preflight requests

Description

I have noticed through testing and looking at the source code that the auth middleware from the express-oauth2-jwt-bearer package is checking for credentials for all requests. The potential issue here is that credentials are not meant to be included in CORS-preflight OPTIONS requests, yet the middleware still expects credentials to exist and will dutifully respond with a 401 to the preflight request.

The reason I ran into this situation is that I used your doc examples that apply the middleware with app.use(auth({ ... })). The app.use attaches the middleware to every request, and therefore this issue arises. I feel like the options here are:

  1. Leave it to the developer to decide on what requests to apply the auth middleware to and if they apply it to all requests, then cross-origin requests will not work.
    • This might benefit from a call out in the docs, otherwise the behavior can be hard to reason about.
    • Alternatively, the docs could be updated to apply the middleware to specific routes like: app.get('/', auth({ ... }), handler)
  2. The auth middleware explicitly skips OPTIONS requests because it shouldn't expect credentials to be included.

I can see why this middleware would want to remain un-opinionated about things like this, but please let me know what you think. I'd be happy to contribute a PR if that would be helpful.

References:

Reproduction

Using the example in your getting started section:

  • Start the express app server on localhost:8080 using your example as a start
  • Start some other application that serves a webpage on localhost:3000
  • Make a cross-origin request from that webpage (from localhost:3000 to localhost:8080)
  • The CORS-preflight OPTIONS request will fail

Environment

"express": "^4.17.1",
"express-oauth2-jwt-bearer": "^1.0.1",

Document and clarify advantages of using this vs express-jwt and jwks-rsa

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

Currently, there is an inconsistency in the documentation regarding Node.js quickstarts.

Is there some documentation about which libraries are recommended and why?
What was the rationale behind creating this new library express-oauth2-jwt-bearer?
To me, it looks like it contains both features of express-jwt and express-jwt-permissions all in one, which is nice. Is that the main advantage?

Describe the ideal solution

  1. Align Quickstart documentation.
  2. Document what the advantages of this lib are over express-jwt
  3. (optional) Migration guide express-jwt to express-oauth2-jwt-bearer

Alternatives and current work-arounds

A clear and concise description of any alternatives you've considered or any work-arounds that are currently in place.

Additional context

Add any other context or screenshots about the feature request here.

Usage without express

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

I'm trying to implement your Getting started guide on nodejs with a Koa server, not express. I would like this to work without having to manually code everything.

Describe the ideal solution

Would it be possible to simply export some lower level functions that can be used by any HTTP js framework. I think all I would need is the published module to export getToken and verify in addition to the actual express middleware. Then I'd ba able to use it with any HTTP framework

Alternatives and current work-arounds

The only work around I see now is re-implementing most of what is done in this repo manually. Or copy/paste or fork.

express-oauth2-jwt-bearer README 'audience' href links to localhost

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

Clicking 'audience' in the README for express-oauth2-jwt-bearer takes you to http://localhost:8000/docs/interfaces/authoptions.html#audience

Provide a clear and concise description of the issue, including what you expected to happen.

Reproduction

Click 'audience' in the README for express-oauth2-jwt-bearer

Detail the steps taken to reproduce this error, what was expected, and whether this issue can be reproduced consistently or if it is intermittent.

Where applicable, please include:

  • Code sample to reproduce the issue
  • Log files (redact/remove sensitive information)
  • Application settings (redact/remove sensitive information)
  • Screenshots

Environment

n/a

Please provide the following:

  • Version of this library used:
  • Version of the platform or framework used, if applicable:
  • Other relevant versions (language, server software, OS, browser):
  • Other modules/plugins/libraries that might be involved:

Supported engines does not include the latest node LTS, 18.12.0

Description

The new node LTS has now entered support, 18.12.0, and consuming application CI steps that target the latest LTS are now broken, as this version is not included in the supported engines.

Reproduction

  1. Install node 18.12.0 (or use a hosted CI agent that targets it as the latest LTS)
  2. Reference the library from a project
  3. Run either npm install or npm ci

Step 3 results in a code EBADENGINE error due to 18.12.0 not falling within the allowed engines spec: {"node":"12.19.0 || ^14.15.0 || ^16.13.0"}

Environment

  • Library version for our incident: [email protected]
  • node version: 18.12.0
  • System: Github-hosted Actions agent, Ubuntu LTS 20.04.5

"nbf" claim timestamp check failed

Checklist

  • I have looked into the Readme and Examples, 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.

Description

The verify will failed due the "nbf" claim check. In this code.

There is a options object as third optional args. If no set this args then jose will set tolerance to 0. It will leads to the JWT verify failed.

Your code validate the iat & exp with clockTolerance, so the clockTolerance should pass to jose as well.

Reproduction

  1. Generate JWT token with nbf claim. The value can be current timestamp + 300
  2. Set auth({clockTolerance: 600, issuer:'your issuer', audience: 'your audience'})
  3. Call your api

Additional context

No response

express-oauth2-jwt-bearer version

audience

Node.js version

18.17.1

Audience Checking shouldn't be forced

Checklist

  • I have looked into the Readme and Examples, 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.

Description

According to https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 the audience claim is OPTIONAL. I'm trying to verify a token without an audience by not providing the audience parameter to this library, but this doesn't appear to be supported.

Reproduction

  1. Leave audience undefined
  2. Assertion in code checks for defined audience => error

Additional context

No response

express-oauth2-jwt-bearer version

1.6.0

Node.js version

18.18.2

Crashed my express server.

Checklist

  • I have looked into the Readme and Examples, 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.

Description

I made a mistake in my client's authentication code, and it crashed my server.

Reproduction

I have been running a development express server without any problem for some time. I made an error in the client, which I have fixed. But, I was able to crash the express server. I don't want this, or any error, to crash the server, I just want an error message, or rejected request. I don't know where to start with this error:
InvalidTokenError: Invalid Compact JWS
at /home/dave/Desktop/AAA/PrizeKick/App/api3/node_modules/express-oauth2-jwt-bearer/dist/index.js:300:19
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /home/dave/Desktop/AAA/PrizeKick/App/api3/node_modules/express-oauth2-jwt-bearer/dist/index.js:403:24

Obviously I am doing something wrong but the server crashed and I don't want someone else to crash the server.

Additional context

No response

express-oauth2-jwt-bearer version

1.6.0

Node.js version

v20.10.0

Support node 16.10

Description

The engines supported here require node ^16.13.0, but there are memory issues with latest node 16 and Jest. See jestjs/jest#7874 (comment).

The workaround for this is to use node 16.10 with jest. Is there any reason you really need to require 16.13 or higher? If not can it please be dropped? Seems a bit arbitrary, but maybe there is a reason.

Reproduction

Running on our 16.10 image we get: error [email protected]: The engine "node" is incompatible with this module. Expected version "12.19.0 || ^14.15.0 || ^16.13.0".

Environment

Node 16.10

Node version limit

Hello,

I tried to install the package on my node/express project but I got an error because my version node version (16.x.x or 17.x.x) is not supported. Right now node 16 version isLTS but I think you could have just a minimum version of node support, and not a range.

Thank you.

How to stop node-oauth2-jwt-bearer from polluting my output

I am using this package for an express app running on AWS Lambda which prints all output to CloudWatch:

import { auth } from 'express-oauth2-jwt-bearer';

export default auth({
  jwksUri: ...,
  issuer: ...,
  audience: ...,
});

The issue is that every time someone tries to access my endpoints with an expired token (or invalid, or without token), the package throws some errors such as this one:
InvalidTokenError: "exp" claim timestamp check failed

Question:
How do I catch those before they hit the console? I don't want them to reach CloudWatch at all.

I tried wrapping the code with try/catch but it doesn't stop the error from going to console:

const authFn = auth({...});

export default async (req, res, next) => {
  try {
    const result = await authFn(req, res, next);
  } catch(e) {
    // handle error
  }
};

Document upgrade path from "express-jwt" + "jwks-rsa"

Describe the problem you'd like to have solved

Previously, the official Auth0 docs recommended the use of express-jwt + jwks-rsa for Express APIs.
Therefore, many people might want to crossgrade from these libs to express-oauth2-jwt-bearer,
especially since the sub-dependency footprint was reduced a lot - 35 vs. 2 packages 🎉

Describe the ideal solution

The documentation should describe things to consider when crossgrading from express-jwt + jwks-rsa to express-oauth2-jwt-bearer.

  • how to adapt the code (okay this one is more or less clear):
    Mostly change from req.user or req.auth to req.auth?.payload
  • are error handling, retries, timeouts different (e.g. when fetching the public key)?
  • is anything no longer supported, compared to the previous libs?
  • any other changes in behavior that might not be obvious

Alternatives and current work-arounds

Developers can try to figure out themselves, and discover unexpected changes in production.

Additional context

n/a

Proxy Configuraton Broken/HTTP(S) Agent not being passed on JWKSet Creation

v.1.4.0 of the library is broken when running behind a proxy

The "agent" parameter which is passed to the get-key-function isn't listed as an input parameter in the JWKSOptions, it should be put here:

the "agent" input parameter should then also be passed to the createRemoteJWKSet function in this line:

[docs] API documentation of auth middleware should mention "req.auth"

The current API documentation describes the auth middleware as "Middleware that will return a 401 if a valid JWT bearer token is not provided in the request."

The documentation does not mention req.auth which I would say is also a major part.

You could just reuse this text from the readme:


Successful requests will have the following properties added to them:

app.get('/api/messages', (req, res, next) => {
  const auth = req.auth;
  auth.header; // The decoded JWT header.
  auth.payload; // The decoded JWT payload.
  auth.token; // The raw JWT token.
});

[docs] Node.js 18 support

Describe the problem you'd like to have solved

Latest Node.js LTS (currently v18.x) should be officially supported.
I tested it on localhost, it worked fine, but I didn't run it in production yet.

Describe the ideal solution

See above

Alternatives and current work-arounds

It seems to work "out of spec" with Node 18.

Additional context

The offending documentation is here:

https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md

Requirements
This package supports the following tooling versions:
Node.js: ^12.19.0 || ^14.15.0 || ^16.13.0

-> Please update this to include ^18.12.0 (consistently with package.json)

Export `jwtVerifier` in express-oauth2-jwt-bearer

Describe the problem you'd like to have solved

I'm currently securing an API using this library, which has been working great. But now I find myself looking at ways to also add some security to websocket connections.

Currently the only way to access the features of access-token-jwt is to use the middleware provided by express-oauth2-jwt-bearer.

It would be nice to have a way to access some of these from express-oauth2-jwt-bearer exports.

Describe the ideal solution

import { jwtVerifier } from 'express-oauth2-jwt-bearer'

// Yay! I can verify tokens without having to use middleware
const verifyJwt = jwtVerifier(opts)

Alternatives and current work-arounds

I'm currently mocking the (req, res, next) function arguments for the middleware in order to make this work that goes something like this... which is quite messy, especially with typescript 😅

import { auth } from 'express-oauth2-jwt-bearer'

// ...

const auther = auth({})

const mockAuth = (token) => new Promise((resolve, reject) => {
  const req = {
    /* .. some stuff here */
    headers: {
      authorization: `Bearer ${token}`
    }
  }

  const res = {}

  auther(req, res, (error) => error ? reject(error) : resolve())
})

// ...

router.use(auther)

app.ws('/path', (ws, upgradeReq) => {
  /* Some stuff here that can verify the upgradeReq (cookie value) as well as any ws
     messages (w/embedded token) using mockAuth(token) and then do a ws.close() with
     custom code and reason to make client-side app display correct message */
})

The only proper alternative looks to be installing other libraries to handle the same job.

Additional context

Sorry if there's something obvious I'm missing here both in terms of these packages and/or how to best deal with my websocket situation.

[example] How to write unit tests for our Express APIs with canned JWTs?

Describe the problem you'd like to have solved

The basic usage of this library is well documented.

In the real world though, developers also have to write tests.
One kind of test that we would like to have is the following:

  • Testing API requests against our Express API on localhost (e.g. using mocha + supertest).
  • Using canned JWTs (e.g. a malformed one, or one including a particular subject and scopes).
  • The library should ignore both the signature and any timestamps in the JWT, so the test can be run any time later.
  • Since the signature should be ignored, there's also no point in fetching the JWKS in this case.
    E.g. if we rotate our Auth0 signing key, this kind of test should not be affected.

The goal is to use most of the code in node-oauth2-jwt-bearer in these tests, so e.g. the error handling is 99% equal to production.
I'm aware that we can mock away the library entirely, but then we can no longer be sure that our tests match what is happening in production.

Describe the ideal solution

A short guide or example is provided.

Alternatives and current work-arounds

Developers can try to figure out themselves, wasting time.

Additional context

Didn't find what I was looking for here:

Example how I imagine it could work:

const { auth } = require('express-oauth2-jwt-bearer');
const isTest = process.env.NODE_ENV === 'test';

app.use(
    auth({
      issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN',
      audience: 'https://my-api.com',
      unsafeIgnoreSignature: isTest,
      unsafeIgnoreTimestamps: isTest,
    })
);

Alternative example:

const { auth, authMockForTests } = require('express-oauth2-jwt-bearer');
const isTest = process.env.NODE_ENV === 'test';

app.use(
    isTest ?
    // authMockForTests doesn't validate signatures or timestamps, and doesn't load JWKS.
    authMockForTests({
      issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN',
      audience: 'https://my-api.com',
    })
    :
    auth({
      issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN',
      audience: 'https://my-api.com',
    })
);

500 Error thrown when deployed to GCP App Engine

Checklist

  • I have looked into the Readme and Examples, 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.

Description

When an app is deployed to the App Engine in the Google Cloud Platform, and the middleware is defined as follows:

const jwtCheck = auth({
  audience: 'https://MY_AUDIENCE_URL/',
  issuerBaseURL: 'https://MY_ISSUER_URL/',
  tokenSigningAlg: 'RS256',
});

app.use(jwtCheck);

app.get('/', async (req, res) => {
  console.log('Auth: %s', JSON.stringify(req.auth));
  console.log('Headers: %s', JSON.stringify(req.headers));
  console.log('Body: %s', JSON.stringify(req.body));
  console.log('Query: %s', JSON.stringify(req.query));
  const TOKEN_RE = /^Bearer (.+)$/i;
  if (typeof req.headers.authorization === 'string') {
    const match = req.headers.authorization.match(TOKEN_RE);
    if (!!match) {
      res.send(`${match[1]}`);
    }
  }
});

and then a request is sent to the App Engine URL using the CURL protocol, i.e.

curl --verbose --request GET \
  --url https://MY_APP_ENGINE_URL/ \
  --header 'Accept: application/json'  --header 'authorization: Bearer 

the result of the CURL request is a 500 error. The App Engine shuts down because of this request.

However, if the auth check is changed to

const jwtCheck = auth({
  audience: 'https://MY_AUDIENCE_URL/',
  issuerBaseURL: 'https://MY_ISSUER_URL/',
  authRequired: false,
  tokenSigningAlg: 'RS256',
});

then the call to the endpoint succeeds, and the req.auth field is populated correctly.

I suspect that this is because the GCP App Engine generates some kind of preflight request that causes the middleware to throw an error.

Reproduction

  1. Create a GCP App Engine project using the code snippets shown above (without changing the authRequired field).
  2. Deploy the GCP App Engine project.
  3. Create a m2m token using the oauth/token endpoint.
  4. Send a GET request to the / endpoint using the CURL protocol.
  5. Note that the GET request fails with a 500 error.
  6. Go to the App Engine logs, and note that the App Engine server is shut down.
  7. Add authRequired: true to the jwtCheck middleware.
  8. Observe that the GET request succeeds, and the req.auth field is populated.

Additional context

No response

express-oauth2-jwt-bearer version

1.5.0

Node.js version

18.14.0

Allow for JWT to be in headers other than Authorization

Describe the problem you'd like to have solved

The Google API Gateway docs suggest that the Authorization header is forwarded to another header. This header is then base64 encoded. I would like a configuration to be able to use a header name other than authorization. It looks like the change would need to happen here...

https://github.com/auth0/node-oauth2-jwt-bearer/blob/47a64302bd077601701dfcbe34cbdf058431de88/packages/oauth2-bearer/src/get-token.ts

More information on the Google requirements...

https://cloud.google.com/endpoints/docs/openapi/authenticating-users-custom#receiving_authenticated_results_in_your_api

Describe the ideal solution

I can pass a config to bearer.auth to tell it the header name I would like to use.

Alternatives and current work-arounds

Google does still provide the Authorization header, however, they advise against using it.

InvalidTokenError: Failed to fetch authorization server metadata

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

When I click button in the external page I'm expecting to get the response message from the API server.

Instead, I get this error in nodejs server:

InvalidTokenError: Failed to fetch authorization server metadata
    at C:\Users\BUGA\Documents\VSCODE\Web Projects\fuceti-v2\server\node_modules\express-oauth2-jwt-bearer\dist\index.js:271:19
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async C:\Users\BUGA\Documents\VSCODE\Web Projects\fuceti-v2\server\node_modules\express-oauth2-jwt-bearer\dist\index.js:354:24

and I get this error in client side vue:

xhr.js?b50d:210 GET http://localhost:8080/api/external 401 (Unauthorized)
dispatchXhrRequest @ xhr.js?b50d:210
xhrAdapter @ xhr.js?b50d:15
dispatchRequest @ dispatchRequest.js?5270:58
request @ Axios.js?0a06:112
Axios.<computed> @ Axios.js?0a06:136
wrap @ bind.js?1d2b:9
_callee$ @ ExternalApi.vue?ac6e:19
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?1da1:13
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
callApi @ ExternalApi.vue?ac6e:19
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
ExternalApi.vue?ac6e:34 Error: Request failed with status code 401
    at createError (createError.js?2d83:16:1)
    at settle (settle.js?467f:17:1)
    at XMLHttpRequest.onloadend (xhr.js?b50d:66:1)

Reproduction

I followed the quickstart guides:

Environment

Windows 10

Server packages:

"dependencies": {
    "@types/cors": "^2.8.12",
    "cors": "^2.8.5",
    "express": "^4.17.2",
    "express-oauth2-jwt-bearer": "^1.1.0",
    "npm-run-all": "^4.1.5"
  }

Client packages

  "dependencies": {
    "@auth0/auth0-spa-js": "^1.19.4",
    "axios": "^0.25.0",
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-router": "^3.2.0",
    "vuetify": "^2.4.0"
  }

Proposal: add support for `scopesIncludesAny`

Describe the problem you'd like to have solved

express-oauth2-jwt-bearer

Currently for checking scopes there is only one function exposed by the library requiredScopes. It coves the cases, when all provided scopes must be included in the token. However, if there is a need to allow access based on OR condition (i.e. require either scope A or scope B), that can not be implemented without writing custom logic for checking scopes.

Describe the ideal solution

A new utility function called scopesIncludesAny (or something similar) is exposed by the library.
It would work by checking if at least one of the provided scopes exist in the payload.scope property.
I.e. scopesIncludesAny(['A', 'B']) - would return true if:

  • payload contains scope A,
  • payload contains scope B,
  • or payload contains scope A and B.

If there isn't scope A or scope B in the payload, error will be thrown.

Alternatives and current work-arounds

Custom utility function can be written by the library user, which adds missing behaviour.

Node 21.5 support

Checklist

  • I have looked into the Readme and Examples, 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

Working with node 21.5, but noted that this package is not supported

Describe the ideal solution

Consider support for node 21.5

Alternatives and current workarounds

downgrade to most recent 20.x version

Additional context

Would be nice to have, but workaround exists.

Getting AssertionError You must provide a 'tokenSigningAlg' for validating symmetric algorithms despite not providing a secret key value pair.

Checklist

  • I have looked into the Readme and Examples, 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.

Description

const checkJwt = auth({ audience: process.env.AUDIENCE_ID, issuerBaseURL: process.env.ISSUER_BASE_URL, });
I have implemented this middleware for my express backend. However when I run the backend I get the error "AssertionError: You must provide a 'tokenSigningAlg' for validating symmetric algorithms".

Reproduction

  1. Clone https://github.com/auth0-samples/auth0-express-api-samples
  2. Cd /01-Authorization-RS256
  3. Follow installation instructions in readme, and change checkJWT into const checkJwt = auth({ audience: process.env.AUDIENCE_ID, issuerBaseURL: process.env.ISSUER_BASE_URL, }); . Assertion error consistently shown

Additional context

No response

express-oauth2-jwt-bearer version

1.6.0

Node.js version

v16.14.2

InvalidTokenError: Invalid Compact JWS

Description

I'm using the auth middleware to protect a certain endpoint. The issue is when I use the access token (as bearer token) coming from getAccessTokenSilently of @auth0/auth0-react. I'm getting InvalidTokenError: Invalid Compact JWS in the logs. But when I use the __raw claim from getIdTokenClaims, it works. I'm confused whether this lib is suppose to verify access token or ID token.

Reproduction

  1. Set up node-express app (server)
const jwtCheck = auth({
  issuerBaseURL: "<DOMAIN>",
  audience: "<CLIENT_ID>",
});

app.get("/signIn", jwtCheck, async (req, res) => {
  if (req.auth) {
    return res.send("OK");
  }

  return res.status(401).send("Unauthorized");
});
  1. Set up react app (client)
export default function Home() {
  const auth0 = useAuth0();

  function signIn() {
    auth0.loginWithRedirect();
  }

  function signOut() {
    auth0.logout({
      returnTo: window.location.origin,
    });
  }

  useEffect(() => {
    if (auth0.isAuthenticated) {
      auth0.getAccessTokenSilently().then((token) => {
        fetch("/signIn", {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
          .then((res) => res.text())
          .then((text) => console.log(text))
          .catch((error) => console.error(error));
      });
    }
  }, [auth0]);

  if (!auth0.user) {
    return <button onClick={signIn}>Sign In</button>;
  }

  return (
    <div>
      <span>{auth0.user.name}</span>&nbsp;
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}

Environment

Please provide the following:

  • Version of this library used: 1.1.0
  • Version of the platform or framework used, if applicable: [email protected]
  • Other relevant versions (language, server software, OS, browser): typescript, firebase cloud function, firebase hosting
  • Other modules/plugins/libraries that might be involved: @auth0/[email protected]

Provide funtion for checking permissions on a token

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

We are using the Auth0 Core RBAC feature, so we have set up some roles and permissions on the Auth0 dashboard that will be using to control access to some API endpoints over our application. The problem I'm having is I didn't found the way to check for "permissions" instead of "scope" using this library.

This is the function given to check "scopes" but no option for checking other field in the JWT token is given. I can't understand how this library is recommended by Auth0 and has no support over all the features that are given (sold) on the platform.

Describe the ideal solution

The ideal solution I imagine is to add some function like requiredPermissions that will make the same operations over "permissions" field instead of "scopes"

Alternatives and current work-arounds

Currently using the old stack including

express-jwt, and jwks-rsa - For JWT token validation.

express-jwt-permissions - For JWT token permissions validations. You can specify wether the token is on the request and which field to check (scope, permissiosn or whatever the token has)

Additional context

I was trying to use this library instead of the express-jwt, express-jwt-permissions, and jwks-rsa stack following this recent blog post where it recommends to use this library as the other ones would only be maintained and won't get new features or further develpment apart from maintenance.

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.