Using AWS Cognito as authentication provider in ASP.Net Core API. This example uses c# and .NET 5
- AWS Console - AWS console (Requires an AWS Console Account)
- ASP.NET Core Identity Provider for Amazon Cognito - Github repo
-
Setup a UserPool using the AWS console.
- Provide the name of your pool.
- Select Review Defaults
- Select Add app client
- Create the App Client
Make Sure the following is selected:
- Enable username password auth for admin APIs for authentication (ALLOW_ADMIN_USER_PASSWORD_AUTH)
- Enable username password based authentication (ALLOW_USER_PASSWORD_AUTH)
- Enable SRP (secure remote password) protocol based authentication (ALLOW_USER_SRP_AUTH)
- Select Create app client.
- Select Return to pool details.
- Select Create pool.
- Provide the name of your pool.
-
Get AWS Ids & Secrets
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 5.0.14
Install-Package Amazon.AspNetCore.Identity.Cognito
Install-Package Amazon.Extensions.CognitoAuthentication
Install-Package AWSSDK.CognitoIdentityProvider
For a development user pool edit either the appsettings.Development.json file or the projects secrets.json file.
"AWS": {
"Region": "<your region id goes here>",
"UserPoolClientId": "<your user pool client id goes here>",
"UserPoolClientSecret": "<your user pool client secret goes here>",
"UserPoolId": "<your user pool id goes here>"
}
Note: If using appsettings.Development.json or some other file in your project structure be careful checking in secrets to source control.
public void ConfigureServices(IServiceCollection services)
{
// Adds Amazon Cognito as Identity Provider
services.AddCognitoIdentity();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = $"https://cognito-idp.{this.config.AWS.Region}.amazonaws.com/{this.config.AWS.UserPoolId}";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = $"https://cognito-idp.{this.config.AWS.Region}.amazonaws.com/{this.config.AWS.UserPoolId}",
ValidateLifetime = true,
LifetimeValidator = (before, expires, token, param) => expires > DateTime.UtcNow,
ValidateAudience = false,
};
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// If not already enabled, you will need to enable ASP.NET Core authentication
app.UseAuthentication();
...
}
- None