Created
April 15, 2020 21:39
-
-
Save joawan/8266d6ebc2ae777211d9a0c32ccfc1ed to your computer and use it in GitHub Desktop.
Token introspection as Express middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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