Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Contributions for cognito-express #28

Open
philippefutureboy opened this issue Sep 18, 2019 · 1 comment
Open

Contributions for cognito-express #28

philippefutureboy opened this issue Sep 18, 2019 · 1 comment

Comments

@philippefutureboy
Copy link

philippefutureboy commented Sep 18, 2019

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

@ghdna
Copy link
Owner

ghdna commented Sep 19, 2019

Thank you, I'll check it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants