reactjsasp.net-corejwtamazon-cognitoawscognitotoken

.NET Cognito Authentication JWTBearer


SCENARIO

I am trying to provide authentication for my web application APIs with AWS-Cognito and JWTBearer.

PROBLEM

Currently, my client performs a GET call and is met with a 401 (Unauthorized) message. This prompts the client to redirect to Cognito UI for log-in and the token. Once performed, we're turned back to the web application.

When the token has been provided, I attach it to a header and perform the request again. This doesn't get validated by the server, and we end up in a loop.

It feels as though JWTBearer is not doing anything.

SERVER .NET 5.0

Startup.cs

public void ConfigureServices(IServiceCollection services)
{

...

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    
                    options.Authority = "https://{domain}.{location}.amazoncognito.com/{PoolId}";
                    options.Audience = "http://localhost:5000";
                });
...
}
public void Configure(iApplicationBuilder app, IWebHostEnvironment env)
{

...

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

...

}

Controller

[HttpGet]
[Authorize]
public async Task<IActionResult> GetItems(ICollection<Data> collection){...}

CLIENT React

//Token = "Bearer AccessToken"

fetch(config.getResourceUrl, {headers: {Authentication: Token}})
    .then(res => {
        if (res.status > 400) {
            window.location.replace("{Cognito UI}");
        } else {
            return res.json();

        })

Solution

  • Solved the problem:

    fetch(config.getResourceUrl, {headers: {Authentication: Token}})
    

    The header should have read Authorization instead.

    fetch(config.getResourceUrl, {headers: {Authorization: Token}})