AWS Cognito — Client credentials flow .NET 6
Tags: aws, dotnet, cognito, api
Published: 2022-05-30 14:55:42

## AWS Cognito User pool creation

Navigate to the AWS Cognito service page

Click on create user pool


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xowsh1tb5fw7v21vcwvt.png)

### Step 1: **Configure sign-in experience**

Select Email and click next


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0dyfbjftcb4gkhn4spho.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fg1utqde501f2nswe5ay.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy8cez01twtbaenhaqe0.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/568k0gdjf2ryhmk6g6t8.png)

### Step 3: Configure sign-up experience

Keep all selections as default and click next


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11tq51nygov0j0ymqiuh.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0b4fr89xuxlqrndfe47.png)

### Step 4: **Configure message delivery**

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0k59cwdphbe9zdln3wg.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9vgz9af4a6v0wdf1v32.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3gpmgqg25e4c2c7nbij.png)

### Step 6: **Review and create**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5sal74yfrgg0v17e9gm.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25zene72ftbvl71nbizu.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cklblx87a4y48fujm7t2.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uromd0g6hk29qml9cdrm.png)

- Review your configuration
- Click Create user pool

### User Pools


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l56ru5xu2zi969tovlug.png)

See your created user pool 

## Application configuration and resource server creation

Navigate to your created user pool


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vvq76ipc8qajnvlr2ru.png)

Navigate to the App Integration tab


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/14vpqzmqpfehciszazts.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6eipb86s8bobrqe1mgg.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzwiexx7ox1p60uik327.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3a54busbwym99dttnhv.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lbxls42vt70ydxq81vcc.png)


### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zydmkutei884mlb94dgc.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7943pkfdtkmq9g6ajzy.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssk8d6bdabob5b2jkgwi.png) 

## Create Weather API

### Step 1: Create API

Create a API project if you don’t have one


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24eegflzlf0ey9t2z4v7.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6o86nq06uilbmi6rzw4o.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4hve021n5sz0h3ikbzf.png)

### Step 2: Add NuGet packages

Add the following NuGet packages:

- [https://www.nuget.org/packages/Amazon.AspNetCore.Identity.Cognito/](https://www.nuget.org/packages/Amazon.AspNetCore.Identity.Cognito/)
- [https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer](https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/6.0.5)/


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9pn0hzom790oswoztvw1.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gisbzfuru9yg4eq9ppe3.png)

### Step 3:  Setup auth in Program.cs

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

```csharp
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
    };
});
```

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

```json
app.UseAuthentication();
app.UseAuthorization();
```

Add the following using's to the Program.cs

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

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

```json
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();
```

### 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](https://cognito-idp/).{region}.amazonaws.com/{userpoolid}

```json

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

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/doame0m5l1fo0hdx3ag1.png)

### 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.

```json
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();
        }
    }
}
```

## Call the Weather Forecast API using Postman

### Step 1: Create new collection

- Create a new collection for the API
- Add new request to the collection for the weather forcast endpoint ([https://localhost:7214/WeatherForecast](https://localhost:7214/WeatherForecast))


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aeljxi65815zts9dpo9y.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9kzrwz267z4kcvxpyi0s.png)



### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nai6tefg7742n0907eid.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mfjnw2yp68a4jpl9he95.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjc9ofghcbmsj3wjahsg.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cbebxmgccvb2xuuf3x93.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cm262okes8xeqf6fyt1a.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ciz4i96b5gtds9ezbsu.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pflduqxem8e33ntijvvt.png)

### Step 3: Call the Weather API

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlxb3ddb5ojwt4h4v1sv.png)

It’s as easy as that !🎉

You can have a look at the repo below to find the full codebase.
https://github.com/Bassonrichard/aws-cognito-weather-api