Created
March 2, 2020 15:07
-
-
Save bmorrisondev/f74187a06164a957295509373eecea09 to your computer and use it in GitHub Desktop.
An express.js authentication middleware using AWS Cognito & the CognitoExpress package
This file contains hidden or 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 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