DEV Community

Cover image for AWS Cognito — Client credentials flow .NET 6
Richard Basson
Richard Basson

Posted on • Updated on

AWS Cognito — Client credentials flow .NET 6

AWS Cognito User pool creation

Navigate to the AWS Cognito service page

Click on create user pool

Image description

Step 1: Configure sign-in experience

Select Email and click next

Image description

Step 2: Configure security requirements

  • Under password policy select cognito defaults
  • Under Multi-factor authentication select No MFA
  • Under User account recovery select Enable self-service account recovery and then Email Only
  • Click next

Image description

Image description

Image description

Step 3: Configure sign-up experience

Keep all selections as default and click next

Image description

Image description

Step 4: Configure message delivery

Select Send email with Cognito and keep the rest of the configuration as default then click next

Image description

Step 5: Integrate your app

  • Configure the User pool name with your preferred naming convention
  • Select Confidential client
  • Configure the App client name
  • Click next

Image description

Image description

Step 6: Review and create

Image description

Image description

Image description

Image description

  • Review your configuration
  • Click Create user pool

User Pools

Image description

See your created user pool

Application configuration and resource server creation

Navigate to your created user pool

Image description

Navigate to the App Integration tab

Image description

Step 1: Create Domain

  • On the Domain section click on Actions and then click on Create Cogniro domain
  • Enter a unique domain prefix
  • Click Create Cognito domain

Image description

Image description

Step 2: Create Resource server

  • Click Create resource server
  • Configure the resource server name and identifier
  • Create custom scopes for your application to use when authenticating
  • Click create resource server

Image description

Image description

Step 3: Configure client application

  • Select the app client you created
  • Under Hosted UI click edit
  • Under Hosted sign-up and sign-in pages select the identity provider cognito user pool
  • Select Client Credentials OAuth 2.0 Grant type
  • Select the custom scope you created and want to assign to the application
  • Click Save changes

Image description

Image description

Image description

Create Weather API

Step 1: Create API

Create a API project if you don’t have one

Image description

Image description

Image description

Step 2: Add NuGet packages

Add the following NuGet packages:

Image description

Image description

Step 3: Setup auth in Program.cs

Add this block of code to the Program.cs under the builder.

builder.Services.AddCognitoIdentity();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["AWSCognito:Authority"];
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
                ValidateAudience = false
    };
});
Enter fullscreen mode Exit fullscreen mode

Add the following under app.UseHttpsRedirection(); in Program.cs

app.UseAuthentication();
app.UseAuthorization();
Enter fullscreen mode Exit fullscreen mode

Add the following using's to the Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
Enter fullscreen mode Exit fullscreen mode

Your Program.cs will end up looking like this when you’re done.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddCognitoIdentity();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["AWSCognito:Authority"];
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        ValidateAudience = false
    };
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
Enter fullscreen mode Exit fullscreen mode

Step 4: Setup configuration file

Add this section to the appsettings.Development.json file

This URL for the authority is made up of the following

https://cognito-idp.{region}.amazonaws.com/{userpoolid}


  "AWSCognito": {
    "Authority": "[https://cognito-idp](https://cognito-idp/).{region}.amazonaws.com/{userpoolid}"
  }
Enter fullscreen mode Exit fullscreen mode

You can find the user pool id in AWS on the Amazon Cognito page under user pools

Image description

Step 5: Add authorize attribute to GetWeatherForecast endpoint

In the WeatherForecastController.cs add the Authorize attribute to the GetWeatherForecast endpoint and add Microsoft.AspNetCore.Authorization to the usings.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AWSCognitoWeatherAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [Authorize]
        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Call the Weather Forecast API using Postman

Step 1: Create new collection

Image description

Image description

Step 2: Setup Collection Auth

  • Click on the Weather Forcast API collection and navigate to the Authorization tab
  • From the Type dropdown select OAuth 2.0
  • In the Configure New Token Section give the token a name
  • In Grant Type dropdown select Client Credentials
  • In the app integration section of the user pool in AWS get the domain url
  • Add the domain to the Access Token URL section in postman and append it with /oauth2/token
  • Get the client id from the client app in AWS
  • Get the client secret from the client app in AWS
  • Get the custom scope form the Hosted UI
  • Add the clientid, client secret and scope in postman
  • Click get new access token
  • Click use token on the pop-up
  • On the Weather Forecast request under the Authorization tab ensure the Type is set to Inherit auth from parent.

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Step 3: Call the Weather API

Click send on the weather forecast request to get the response on the API

Image description

It’s as easy as that !🎉

You can have a look at the repo below to find the full codebase.
https://github.com/Bassonrichard/AWSCognitoWeatherAPI

Discussion (2)

Collapse
arlemi profile image
Arlemi

The last image doesn't load for me. :( Great article otherwise!

Collapse
bassonrichard profile image
Richard Basson Author

I will try fix it , the editor bugged out a bit with all the images 😁