You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# .NET中用极简配置实现基于外部授权服务器的REST API安全

在.NET中实现基于AWS Cognito的纯资源服务器(保护REST API)

你要的纯资源服务器方案,在.NET里可以通过Microsoft.AspNetCore.Authentication.JwtBearer组件实现,完全不需要关联用户管理逻辑,和你Spring Boot里的配置逻辑对应,步骤如下:

1. 安装依赖包

通过.NET CLI安装JWT认证组件:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

或者在Visual Studio的NuGet包管理器中搜索安装同名包。

2. 配置认证与授权(.NET 6+ 顶级语句示例)

在Program.cs中添加认证服务配置,指定AWS Cognito作为授权服务器:

var builder = WebApplication.CreateBuilder(args);

// 注册JWT Bearer认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // AWS Cognito的Authority地址,格式为 https://cognito-idp.{区域}.amazonaws.com/{用户池ID}
        options.Authority = "https://cognito-idp.{your-region}.amazonaws.com/{your-user-pool-id}";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = options.Authority,
            ValidateAudience = false, // 如果你的Cognito令牌不需要验证Audience,设为false;否则配置对应的ValidAudience
            ValidateLifetime = true
        };
    });

// 注册授权服务
builder.Services.AddAuthorization();

// 添加控制器支持
builder.Services.AddControllers();

var app = builder.Build();

// 启用认证中间件(必须在授权中间件之前)
app.UseAuthentication();
// 启用授权中间件
app.UseAuthorization();

app.MapControllers();

app.Run();

3. 可选:通过配置文件管理参数(对应Spring Boot的属性配置)

如果想把认证参数放到配置文件中,修改appsettings.json:

{
  "Authentication": {
    "JwtBearer": {
      "Authority": "https://cognito-idp.{your-region}.amazonaws.com/{your-user-pool-id}",
      "TokenValidationParameters": {
        "ValidateIssuer": true,
        "ValidIssuer": "https://cognito-idp.{your-region}.amazonaws.com/{your-user-pool-id}",
        "ValidateAudience": false,
        "ValidateLifetime": true
      }
    }
  }
}

然后在Program.cs中绑定配置:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        builder.Configuration.Bind("Authentication:JwtBearer", options);
    });

完成以上配置后,所有控制器接口都会被自动保护,请求必须携带Authorization: Bearer {你的访问令牌}头才能访问,和你在Spring Boot中实现的效果完全一致,全程不需要涉及用户注册、登录等管理逻辑,纯资源服务器模式。

内容的提问来源于stack exchange,提问作者Spiky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:00:24