Search code examples
oauth-2.0passport.jsamazon-cognitoidp

How to use AWS Cognito as a provider in Passport?


I have a Javascript backend (NestJS with Express + Passport).

I would like to outsource the complexity of authentication (e.g. social auth) to Cognito but avoid getting locked in. I was wondering if I can use Cognito as a provider in Passport, similar to social providers (Google, Facebook, etc). That way, I could integrate many providers with the effort of integrating just one. I would still manage user data, authorization, etc in my own app, therefore, if I wanted to in the future, I could implement Google, Facebook, etc. social auth in my own app and get rid of Cognito.

If I understand it correctly this is possible with Auth0.

Ideally, I would like to implement an OAuth flow where the user is redirected to a simple "sign up / log in" Cognito app, logs in, gets redirected to a callback URL in my app where I receive user data. If AWS doesn't host a solution for this, I can also use their UI elements to build & host this app.

If implemented as a provider / strategy, this could be as simple as:

passport.use(new CognitoStrategy({
    key: KEY,
    secret: SECRET,
    callbackURL: "http://www.example.com/auth/cognito/callback"
  },
  function(token, tokenSecret, profile, done) {
      User.findOrCreate({ uuid: profile.id }, function (err, user) {
        return done(err, user);
      });
  }
));

app.get('/auth/cognito', passport.authenticate('cognito'));
app.get('/auth/cognito/callback', 
  passport.authenticate('cognito', { failureRedirect: '/auth/cognito' }),
  function(req, res) {
    res.redirect('/');
  });

Is there a solution for this? Does this make sense in principle? Am I missing any complexity in the many-for-one idea?

Related resources:


Solution

  • It's possible to use both User Pools and Identity Pools via OAuth. Cognito even has a self-hosted UI, with own domain & branding available. Setup steps: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html

    I used a generic OAuth2 Passport strategy: https://github.com/jaredhanson/passport-oauth2

    Endpoint details: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html

    After the setup, Federated Identities can be set up from the AWS console.

    In the end an unbranded screen looks like this:

    enter image description here