AWS Cognito User pool creation
Navigate to the AWS Cognito service page
Click on create user pool
Step 1: Configure sign-in experience
Select Email and click next
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
Step 3: Configure sign-up experience
Keep all selections as default and click next
Step 4: Configure message delivery
Select Send email with Cognito and keep the rest of the configuration as default then click next
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
Step 6: Review and create
- Review your configuration
- Click Create user pool
User Pools
See your created user pool
Application configuration and resource server creation
Navigate to your created user pool
Navigate to the App Integration tab
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
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
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
Create Weather API
Step 1: Create API
Create a API project if you don’t have one
Step 2: Add NuGet packages
Add the following NuGet packages:
- https://www.nuget.org/packages/Amazon.AspNetCore.Identity.Cognito/
- https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/
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
};
});
Add the following under app.UseHttpsRedirection(); in Program.cs
app.UseAuthentication();
app.UseAuthorization();
Add the following using's to the Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
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();
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}"
}
You can find the user pool id in AWS on the Amazon Cognito page under user pools
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"
};
</span><span class="err">private</span><span class="w"> </span><span class="err">readonly</span><span class="w"> </span><span class="err">ILogger<WeatherForecastController></span><span class="w"> </span><span class="err">_logger;</span><span class="w">
</span><span class="err">public</span><span class="w"> </span><span class="err">WeatherForecastController(ILogger<WeatherForecastController></span><span class="w"> </span><span class="err">logger)</span><span class="w">
</span><span class="p">{</span><span class="w">
</span><span class="err">_logger</span><span class="w"> </span><span class="err">=</span><span class="w"> </span><span class="err">logger;</span><span class="w">
</span><span class="p">}</span><span class="w">
</span><span class="p">[</span><span class="err">Authorize</span><span class="p">]</span><span class="w">
</span><span class="p">[</span><span class="err">HttpGet(Name</span><span class="w"> </span><span class="err">=</span><span class="w"> </span><span class="s2">"GetWeatherForecast"</span><span class="err">)</span><span class="p">]</span><span class="w">
</span><span class="err">public</span><span class="w"> </span><span class="err">IEnumerable<WeatherForecast></span><span class="w"> </span><span class="err">Get()</span><span class="w">
</span><span class="p">{</span><span class="w">
</span><span class="err">return</span><span class="w"> </span><span class="err">Enumerable.Range(</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">5</span><span class="err">).Select(index</span><span class="w"> </span><span class="err">=></span><span class="w"> </span><span class="err">new</span><span class="w"> </span><span class="err">WeatherForecast</span><span class="w">
</span><span class="p">{</span><span class="w">
</span><span class="err">Date</span><span class="w"> </span><span class="err">=</span><span class="w"> </span><span class="err">DateTime.Now.AddDays(index)</span><span class="p">,</span><span class="w">
</span><span class="err">TemperatureC</span><span class="w"> </span><span class="err">=</span><span class="w"> </span><span class="err">Random.Shared.Next(</span><span class="mi">-20</span><span class="p">,</span><span class="w"> </span><span class="mi">55</span><span class="err">)</span><span class="p">,</span><span class="w">
</span><span class="err">Summary</span><span class="w"> </span><span class="err">=</span><span class="w"> </span><span class="err">Summaries</span><span class="p">[</span><span class="err">Random.Shared.Next(Summaries.Length)</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="err">)</span><span class="w">
</span><span class="err">.ToArray();</span><span class="w">
</span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
}
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)
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.
Step 3: Call the Weather API
Click send on the weather forecast request to get the response on the API
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
Top comments (3)
The last image doesn't load for me. :( Great article otherwise!
I will try fix it , the editor bugged out a bit with all the images 😁
How to create controller for sign up and sign in? :)