Skip to content

Instantly share code, notes, and snippets.

@joawan
Created April 15, 2020 21:39
Show Gist options
  • Save joawan/8266d6ebc2ae777211d9a0c32ccfc1ed to your computer and use it in GitHub Desktop.
Save joawan/8266d6ebc2ae777211d9a0c32ccfc1ed to your computer and use it in GitHub Desktop.
Token introspection as Express middleware
const tokenIntrospection = require('token-introspection');
const createError = require('http-errors');
const wrap = (fn) => (...args) => fn(...args).catch(args[2]);
const introspectMiddleware = (opts = {}) => {
const introspect = tokenIntrospection(opts);
return wrap(async (req, res, next) => {
try {
req.token = await introspect(req.token, 'access_token');
next();
} catch (err) {
if (err instanceof tokenIntrospection.errors.TokenNotActiveError) {
throw new createError.Unauthorized(err.message);
}
throw new createError.InternalServerError('An unknown error occurred when introspecting token');
}
});
};
// Then use the middleware
app.use(introspectMiddleware({ jwks_uri: 'https://example.com/jwks' }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment