Cognito JWT Authorize in ASP.NET Core 6 Web API

502548928:
Yaron

How can I configure my ASP.NET Core 6 Web API controllers to use AWS Cognito authorization?

This is the code I wrote in my program.cs file:

var AWSconfiguration = builder.Configuration.GetSection("AWS:Cognito");
var userPoolId = AWSconfiguration["UserPoolId"];
var clientId = AWSconfiguration["ClientId"];
var region = AWSconfiguration["Region"];

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}";
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidIssuer = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}",
        ValidAudience = clientId,
        
    };
});

I'm getting this error:

www-authenticate: Bearer error="invalid_token",
error_description="The audience 'empty' is invalid"

I validated my clientID in the AWS console.

Thanks for the help

Gary Archer

Cognito access tokens don't have an audience claim - though ideally they should. In other authorization servers, APIs check the received access token has the expected logical name, such as api.mycompany.com.

For Cognito you will need to configure .NET to not validate the audience, similar to this. Other token validation parameters are derived from the metadata endpoint derived from the issuer base URL:

private void ConfigureOAuth(IServiceCollection services)
{
    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = this.configuration.IssuerBaseUrl;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
            };
        });

    services.AddAuthorization(options => 
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    });
}

The FallbackPolicy then ensures that authentication is applied globally, except for endpoints annotated with [AllowAnonymous].

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do you Authorize a Web API Controller in ASP Net Core

ASP.NET Core Web API - How to authorize my Web API Request with Basic Auth

ASP.NET Core Web API Facebook JWT Authentication

Check IP with JWT Authorization in ASP.NET Core Web Api

JWT bearer token Authorization not working asp net core web api

JWT Authentication not working in ASP.NEt core web api

Facebook JWT authentication using ASP.NET Core Web API

.net core web api jwt

ASP.NET Core Authorize attribute not working with JWT

How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()

ASP.NET core Web API Authorize Attribute return 404 Error & force redirect

Response compression is not working in ASP.NET Core 6 Web API

ASP.NET Core 6 Web API - serializing public fields

Fluent Validation and ASP.NET Core 6 Web API

transfer JWT Authentication implementation from .net core 2 to asp.net web api 2

ASP.NET Core 3 API Ignores Authorize Attribute with Bearertoken

JWT authentication for ASP.NET Web API

.Net Core Web API Basic Authentication Authorize does not work on Azure

create jwt token in c# asp.net core web api

Using Microsoft Graph token to secure ASP.NET Core Web API with Jwt Bearer tokens

Skip JWT Auth during Tests ASP.Net Core 3.1 Web Api

Give response to JWT wrong Authentication Asp.Net Core Web Api

Validating B2C JWT tokens in Asp.Net Core Web Api

How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?

Is it necessary to create tables like AspNetUsers while adding JWT authentication to ASP.NET Core 2.1 Web API?

ASP.NET Core Web API - JWT Message Handler - No Registered Type Error

Problems combining JWT Bearer Authenticating Web API with Asp.Net Core 2.0

Error generating JWT token during ASP.NET Core Web API authorization

Consuming Web API secured with JWT authentication from ASP.NET Core MVC application