-
Notifications
You must be signed in to change notification settings - Fork 44
Open
Description
Hi!
In the process of ensuring the functionality of my authentication middleware, I have written two pieces of code that you may find interesting for your own usage in cognito-express's development:
- An e2e test suite that tests the basic use-cases for token validation
- A quick & dirty utility script used to force reset the password of a user created via the Cognito User Pool interface
For context, my authenticationMiddleware is implemented as follows:
function authenticationMiddleware(poolOptions = null) {
// Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress(
typeof poolOptions === 'object' && poolOptions !== null
? poolOptions
: {
region: process.env.COGNITO_REGION,
cognitoUserPoolId: process.env.COGNITO_USERPOOL_ID,
tokenUse: 'access', // Possible Values: access | id
tokenExpiration: parseInt(process.env.COGNITO_TOKEN_EXPIRATION, 10),
}
);
cognitoExpress.validate = util.promisify(cognitoExpress.validate);
return async function innerAuthenticationMiddleware(req, res, next) {
// I'm passing in the access token in header under key accessToken
const authJwtToken = req.headers.Authorization;
// Fail if token not present in header.
if (!authJwtToken) {
return res.status(401).send('Access Token missing from header');
}
try {
const authResponse = await cognitoExpress.validate(authJwtToken);
// API has been authenticated. Proceed.
req.locals.user = authResponse;
next();
} catch (err) {
// If API is not authenticated, Return 401 with error message.
return res.status(401).send(err);
}
};
}Hope that these can be of use!
Have a great day π
Cheers,
Phil
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels