Skip to content

Instantly share code, notes, and snippets.

@bmorrisondev
Created March 2, 2020 15:07
Show Gist options
  • Select an option

  • Save bmorrisondev/f74187a06164a957295509373eecea09 to your computer and use it in GitHub Desktop.

Select an option

Save bmorrisondev/f74187a06164a957295509373eecea09 to your computer and use it in GitHub Desktop.
An express.js authentication middleware using AWS Cognito & the CognitoExpress package
const CognitoExpress = require('cognito-express')
exports.validateToken = (req, res, next) => {
if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
let cognitoConfig = {
region: process.env.COGNITO_REGION,
cognitoUserPoolId: process.env.COGNITO_USERPOOL_ID,
tokenUse: 'id',
tokenExpiration: 3600000
}
if(req.headers['bm-cognito-token-type']) {
cognitoConfig.tokenUse = req.headers['bm-cognito-token-type'].toLowerCase()
}
const cognitoExpress = new CognitoExpress(cognitoConfig)
let token = req.headers.authorization.split(' ')[1]
cognitoExpress.validate(token, function(err, response) {
if (err) {
req.user = undefined
res.status(401).json({ error: 'Unauthorized.' })
} else {
req.user = response
next()
}
})
} else {
req.user = undefined
res.status(401).json({ error: 'Unauthorized.' })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment