Authentication and authorization using Cognito in asp.NET
We had a problem that we wanted to authenticate our bunch of services using one source like whenever the user wants to access any of your services he/she will get an access grant from our Auth service and will be able to access all services. We solved this using AWS Cognito. Let see how we were able to crack the problem.
In this example, I will be using C# and .NET 5.
We will achieve this by first creating a user pool using the AWS console.
- Provide the name of your pool.
2. Click on review defaults and it will set up the pool using default settings and you can update according to your requirements.
Now that your pool is created so let us add an app client to integrate our application with this pool.
you need to provide a name to the app client and make sure all the checks are according to what you are seeing in the image.
Create a simple asp.net core web API project and install these packages
In your appsettings.json
You can get UserPoold in the General Settings tab.
and AppClientId and AppClientSecret from AppClients Tab.
Note : AppClientId and UserPoolClientId is same.
Now you need to configure Cognito identity in the ConfigureServices method inside Startup.cs class
Now let's start implementing login functionality using
You need to get these services through DI to implement authentication flows.
This is how you can get access and refresh tokens from Cognito. The first time when the user is created with a temporary password on the first login use has to update the password to get the access tokens. It returns a challenge that a new password is required. So we can check using that challenge and prompt use to update the temporary password.
Update Temporary password
To update temporary passwords we respond to that challenge and pass a new password with any required attributes you specified during the creation of UserPool in the AWS console.
Integrating backend API
Integration of backend API to validate the access token generated from Cognito and grant access to that API if this is passed.
Basically what we do is we check for the valid issuer and expiry of the token by using Cognito authority.
First, you need to configure Authentication Service in Startup.cs class in ConfigureServces method.
Afterwards, you can use the Authorize attribute on your endpoints to accept requests that are authenticated using AWS Cognito
In Addition, you can also implement forgot password and refresh token flows using AWS Cognito refer to this documentation.
If you have any suggestions or any confusion do send me feedback I can help you out in that regard.