Cognito JWT 在 ASP.NET Core 6 Web API 中进行授权

huangapple go评论65阅读模式
英文:

Cognito JWT Authorize in ASP.NET Core 6 Web API

问题

如何配置我的ASP.NET Core 6 Web API控制器以使用AWS Cognito授权?

这是我在program.cs文件中编写的代码:

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,
    };
});

我收到了以下错误:

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

我在AWS控制台中验证了我的clientID。

感谢您的帮助

英文:

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

答案1

得分: 1

Cognito的访问令牌没有受众声明,尽管理想情况下它们应该有。在其他授权服务器中,API会检查接收到的访问令牌是否具有预期的逻辑名称,例如 api.mycompany.com

对于Cognito,您需要配置.NET,以便不验证受众,类似于以下方式。其他令牌验证参数是从基于发行者基本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();
    });
}

然后,FallbackPolicy 确保全局应用身份验证,但排除了带有 [AllowAnonymous] 注释的端点。

英文:

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

huangapple
  • 本文由 发表于 2023年6月1日 22:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定