Skip to content

Instantly share code, notes, and snippets.

@morganney
Created December 24, 2021 15:08
Show Gist options
  • Save morganney/d667128bfb02d7dbc1a8fa4fed2b46d4 to your computer and use it in GitHub Desktop.
Save morganney/d667128bfb02d7dbc1a8fa4fed2b46d4 to your computer and use it in GitHub Desktop.
Express middleware for refreshing an access token with a refresh token
import { TokenSet } from 'openid-client'
import error from 'http-errors'
import debugFactory from 'debug'
const debug = debugFactory('ac:refresh')
/**
* Refreshes an expired token set.
* Requires middleware `oidc` to be called first.
*
* @param {Request} req The express request object
* @param {Response} res The express response object
* @param {Function} next The express next callback
*/
const refreshToken = async (req, res, next) => {
const tokenSet = new TokenSet(req.session.tokenSet)
if (tokenSet.expired()) {
const { client } = req.oidc
debug(`Trying to refresh token set using refresh_token ${tokenSet.refresh_token}`)
try {
const refreshedTokenSet = await client.refresh(tokenSet.refresh_token)
debug('Token set refreshed')
debug(`New refresh_token ${refreshedTokenSet.refresh_token}`)
// Available session stores: https://www.npmjs.com/package/express-session#user-content-compatible-session-stores
req.session.tokenSet = refreshedTokenSet
} catch (err) {
debug(`Unable to refresh token: ${err.message}`)
return res.status(401).json(new error.Unauthorized())
}
}
next()
}
export { refreshToken }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment