auth0 / express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow authorization bearer header to authenticate

qpwo opened this issue · comments

Problem

I'd like to also access my website through some scripts but they can't establish a session with the server.

Ideal solution

Add option auth({allowBearer: true}) which allows a authorization: Bearer $token header as an alternative to Cookie: appSession=.... (Either header can be provided but I suppose not both.)

Alternatives and current work-arounds

Importing from oauth2-jwt-bearer/packages/access-token-jwt/src/jwt-verifier and checking for the header in my own middleware.

To be clear, I mean that something like this would work if the option was set to true:

curl  -H "authorization: Bearer $token" http://localhost:3001/api/secretRoute

Hi @qpwo - thanks for raising this.

Assuming $token is the session, what's stopping you doing

curl -H "cookie: appSession=$token" http://localhost:3001/api/secretRoute

To access your route from a script?

In my case the script's token is just the jwt. I couldn't think of an easy way to issue session tokens for the script.

Hi @qpwo - thanks for sharing that information

If the script's token is your access token jwt, then you can just use the express-oauth2-jwt-bearer middleware directly.

You just need to write some logic that protects your route with either the cookie of the authz header:

const { auth, requiresAuth } = require('express-openid-connect');
const { apiAuth: auth } = require('express-oauth2-jwt-bearer');

app.use(auth({ authRequired: false}));

const apiOrCookieAuth = () => {
  const apiAuth = auth(...args);
  const cookieAuth = requiresAuth();
  return (...args) => {
    if (req.header.authorization) { // Or use a query param, different route, etc...
      return apiAuth(...args);
    }
    return cookieAuth(...args);
  }
}

app.get('/api/secretRoute', apiOrCookieAuth(), (req, res, next) => { ... });

Edit: fixed an issue I noticed in the code example

That's a good solution, thank you!