Skip to content

Contributions for cognito-expressΒ #28

@p-hebert

Description

@p-hebert

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:

  1. An e2e test suite that tests the basic use-cases for token validation
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions