Express with AWS Cognito Auth w/ Typescript (2020)

TDot Code
5 min readJul 28, 2020

There have been countless articles out here that I have read about using cognito with express but most of them are not valid because of the deprecation of amazon-cognito-identity-js npm library :(

Another thing noticed is that express tutorials were using aws-cognito-identity-js library when this is in fact more suitable for frontend applications because it does not make use of the “Secret Hash” for your app. The secret hash insures an extra layer of validation so users don’t directly hit your cognito endpoint and create a bunch of users, unless that suits your use case. So below are a few steps on how to to configure AWS Cognito on Express 2020. I’ve also created a YouTube tutorial if you prefer to watch the coding live :)

Step 1: Setup your express server

Open an empty directory of your choice and run the below commands and I will explain after that each of them do:

npm init -y
npm install express express-validator body-parser
npm install --save-dev typescript @types/express @types/node nodemon ts-node

Here we are initializing our node project and install various dependencies that we will be using later on.

  1. express: The lightweight node http framework
  2. express-validator: Used to validate incoming request body
  3. body-parser: Middleware to process json body
  4. type*: I’m using typescript for the project as well(There is something wrong with people who don’t use typescript)
  5. nodemon: To allow hot reloading files after detected changes

You should now modify your scripts inside package.json so it looks something like this:

In the same directory create a nodemon.json file that looks like this:

After all that is setup create a src folder where all your code will live. Inside the src folder create an app.ts & server.ts file.

server.ts
app.ts file

Create a controllers folder inside the src directory and create a file called home.controller.ts

home.controller.ts

After all this is setup you can run npm run dev which will spin up the express server the port 3000. On the browser of your choice(chrome cough) type down localhost:3000 and you should see a page with text saying “success”

Step 2: Setup authentication routes

Now lets setup some routes that will be consuming request relating to SignIn, SignUp & Verify. Create another file in the “src/controllers” directory with the name auth.controller.ts

Above is our beloved auth controller, we have setup a ValidateBody function that returns validation rules that express-validation will use to make sure we aren’t make unnecessary called to cognito calls with an invalid json body.

Step 3: Setup Cognito on AWS Console

Login to your aws account and open the Cognito service and create a new user pool following the steps below:

  1. Enter a Pool name of your choice & click “Step through settings”
  2. Under “Which standard attributes do you want to require?” make sure birthdate, email, family_name & name are all checked & click “Next Step”
  3. Keep clicking “Next Step” until you reach the App clients and click Add a new app client
  4. Give whatever client name you want and make sure ALLOW_USER_PASSWORD_AUTH is checked and click “Create app client”
  5. Keep clicking “Next Step” and finally click “Create pool”

Step 4: Create your Cognito Service

Just before we start coding out the last few pieces to the congito authentication we need to install a few more npm libraries that are cognito specific.

npm install aws-sdk crypto jsonwebtoken jwk-to-pem node-fetch

We need aws-sdk provided by amazon to use their cognito API, crypto to help create secret hashes, jsonwebtoken to decode access tokens, jwk-to-pem to help transform jwks to pem keys and node-fetch to allow http request from express server.

Lets create a services folder inside the src and make a cognito.service.ts file where all cognito related code as seen below will go.

PS. Use your own clientId and secretHash that aws provided for your app client

cognito.service.ts Pt1
cognito.service.ts Pt2

After all that grunt work is done all that’s left is to import your Cognito service inside your controller and pass the require parameters inside your functions as seen in the screenshot below.

HURRAY!! You can now Register, Verify and Login using cognito! But wait, we still need to authorize the user on our Express backend to make sure the user is who they say they are. So create a middlewares folder inside the src directory and make a “auth.middleware.ts” with the code below. A more in-depth guide can be found in this link: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html

TLDR; we are creating a verifyToken middleware which we can now attach to a controller to check if there is an “Auth” header and extract that value to verify weather it is a legit jwt token that aws provided. All request that need to be authorized will need that header.

Below is an example of a new controller called protected.controller.ts which imports the auth.middleware and applies it to the /secret route

Step 5: Sit back and enjoy scaling to MILLIONS of users!

Congratulations you have successfully setup your secure Express AWS Cognito backend service! You can now expand on this and implement a database transaction that saves additional user information that you would like to manage yourself and apply it to various other routes! Also refer to the video pasted in the beginning if you seem to be stuck! Happy coding! :D

*** Link to Code *** https://github.com/floydjones1/ExpressTSCognito

<meta name=”google-site-verification” content=”Ij3YasJJ4jdHzVbJnz59MJ_SZDfVuTuBk0jtJhMC7N4" />

--

--

TDot Code

Just a software developer with a youtube channel! If you’re interested drop a follow :) https://www.youtube.com/channel/UCUwA7VxRo-uw2eQJ52EkKlQ