Cognito via OAuth2 in NestJS: Outsourcing Authentication Without Vendor Lock-in

Csaba Apagyi
JavaScript in Plain English
2 min readJun 18, 2021

--

Authentication is complex, it would be great to outsource it. But I also want to avoid getting locked in. Can I have my cake and eat it too?

TLDR; Yes! In the nestjs-starter repo, I’m using Cognito through OAuth2 with its hosted UI while keeping all user data in my app. So most of the complexity of authentication is outsourced to a ready-made solution (with possibly the lowest price) and I can replace this strategy any time, for example by implementing social login directly.

This way I’ll get many authentication strategies (Password, Google, Facebook, etc) at the cost of integrating a single OAuth2 provider.

Setup Cognito: create a User Pool, an App Client and configure the Hosted UI. Add the config to the .env file.

Then we’ll use passport-oauth2 , a generic OAuth2 strategy to integrate with Cognito.

The only trick to keep in mind is that the id_token is not exposed to the validate method in this generic strategy, therefore we need to make an extra call.

And that’s the basic Cognito integration! There two more steps to make this a complete authentication flow:

  • Issue a JWT token in the redirect endpoint so that we can handle the user session in the app. You can see how to do that in my OAuth2 in NestJS for social login article.
  • Find or store user data in the validate callback. I’m using a DB with TypeORM Repository in the nestjs-starter repo. You can also learn more from the official docs.

Finally, a way to outsource the complexity of authentication without getting locked in with a provider! You’ll find many more cool features in the repo (https://github.com/thisismydesign/nestjs-starter). I’ve also written about an MVC setup combining Next.js and NestJS, and Automagically Typed GraphQL Queries and Results with Apollo.

More content at plainenglish.io

--

--