Create project

Create new ASP.NET Core Web API project.

Create project

Create project

Choose ASP.NET Core 3.1 and disable Docker support.

Create project

Compile and run the project. You should see the following response:

Run project

Please note the port number, it should correspond to the one in Amazon Cognito configuration: https://localhost:44385/. You may go back to Amazon Cognito and configure app client settings.

Secure the route

OpenWeatherForecastController.cs file and make the following changes:

Add following using statement:

using Microsoft.AspNetCore.Authorization;

Add the Authorize attribute to the Get method in WeatherForecastController:

[HttpGet]
[Authorize]
public IEnumerable<WeatherForecast> Get()

Run the project again. You should see the following error that no authentication scheme was specified:

Run project

Configure .NET Core to utilise Cognito

Add Microsoft.AspNetCore.Authentication.OpenIdConnect Nuget package to the project (please choose 3.1.x version to match .NET Core 3.1 project that you have created):

Run project

Open Startup.cs and add the following references:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

Update the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ResponseType = Configuration["Authentication:Cognito:ResponseType"];
        options.MetadataAddress = Configuration["Authentication:Cognito:MetadataAddress"];
        options.ClientId = Configuration["Authentication:Cognito:ClientId"];
    });
}

Add app.UseAuthentication() call to the Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Open appsettings.json and add the following Authentication section:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "Authentication": {
    "Cognito": {
      "ClientId": "<App client id>",
      "IncludeErrorDetails": true,
      "MetadataAddress": "https://cognito-idp.<Your region>.amazonaws.com/<Pool id>/.well-known/openid-configuration",
      "RequireHttpsMetadata": false,
      "ResponseType": "code",
      "SaveToken": true,
      "TokenValidationParameters": {
        "ValidateIssuer": true
      }
    }
  }
}

Pool Id can be found under General setting in the left menu:

Pool Id

App client id can be found under App client in the left menu:

App client Id

Now when you run the project you should be redirected to the Cognito default user registration/log in form:

Run project

Create an account, confirm it using the verification code or using the Amazon Cognito dashboard. Once registered, you should be redirected to the /weatherforecast endpoint and you should see a result output. This means you have been successfully authenticated.

Run project