3rd party authentication is not something new, it's been there for a while now and its popularity is only increasing. It takes out the hassle of managing security risks (to some extent) and allows you to reduce the time to roll out your applications.
To implement auth in React using cognito we need to do two things:
- Setup AWS side of things (user pools, clients, etc.)
- Hook our AWS Cognito user pool and client with the react app
The user pool is like a user directory where all your users (and their attributes like name, email, password, etc.) are stored.
To create a new user pool, login to the AWS console and go to the AWS Cognito homepage. From there, select "Manage User Pools". Select "Create a User Pool" and give some name to the user pool. Click "Review Defaults" (or "Step through Settings" if you want to configure each step) and then click "Create Pool".
Click "Add an app client", give it any name and make sure you uncheck the box next to "Generate client secret". Leave the rest of the options to their defaults unless you want to change something. Click "Create app client".
AWS Cognito provides you an array of attributes that you can store against a user. The default available attributes (they are based on OpenID Connect Specifications) are:
- given name
- middle name
- family name
- preferred username
- phone number
- updated at
ℹ️ The default attributes can be made required/not-required only at the time of the user pool's creation.
Select the type of the attribute (String or number) you want to add, give it any name (without spaces), define min and max length (number of characters), and check the "Mutable" box. Once done, click "Save changes".
Now the last step is to make new attribute(s) both readable and writable. Go back to "App clients" from the left, click "Show Details", Click "Set attribute read and write permissions" (it will be at the bottom). Check the boxes against the custom attribute(s) and click "Save app client changes"
Clone this repo, install dependencies, replace the aws conf (
src/configs/aws.ts) and start the app.
That's pretty much it. Instead of writing code for each component here, I thought it would be better to just link the repo. The code is pretty self-explanatory, but if you need any help please feel free to leave your queries in the comments.
Complete API reference: Read the official documentation