azure 如何为ASP.NET Core Web API添加附加权限

lf5gs5x2  于 2023-05-18  发布在  .NET
关注(0)|答案(1)|浏览(228)

我有一个ASP.NET Core 6 Web API。下面是程序文件中的代码:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

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.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddEndpointsApiExplorer();

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();

appSettings.json

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "my_client_id",
    "ClientSecret": "client_value",
    "Domain": "my_tenant_id",
    "TenantId": "my_tenant_id",
    "Audience": "https://example.onmicrosoft.com/my_client_id"
}

我用[Authorize]装饰了我的控制器。
在《小提琴手/ Postman 》中我第一次跑

https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token

传入

grant_type (client_credentials), 
client_id (my_client_id), 
client_secret (client_secret),
scope (https://example.onmicrosoft.com/my_client_id/.default)

它返回令牌,允许我将此不记名令牌传递到对Web API的调用中,如果令牌正确,则返回数据,否则返回401错误。
一切如我所料。
我试图添加权限(可能称为RolesScope),以便我可以定制我的API,其中某些方法是只读的,其他方法具有写入权限。
我怎么能做到这一点,因为我找不到任何文档来帮助和其他人不使用AudienceappSettings配置文件(如上所示),但有它作为范围,但我不知道如何将其添加到我目前的代码?

9fkzdhlc

9fkzdhlc1#

要向ASP.NET Core Web API添加权限,请检查此Github Sample code(Thanks @ cilwerner)。

  • 您必须在Azure门户中定义应用注册的范围。并在应用注册中将作用域添加到您的API权限中,并使用作用域配置API。

在应用注册中添加作用域,如下所示。

将作用域添加到API权限
应用注册-API权限。选择Add a permission,然后选择My APIs
在program.cs中使用

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi().AddInMemoryTokenCaches(); 
builder.Services.AddAuthorization(options => { options.AddPolicy("ReadPolicy", policy => policy.RequireClaim("scope", "api://Client_id/read")); 
    options.AddPolicy("WritePolicy", policy => policy.RequireClaim("scope", "api://my_client_id/write")); }); 

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers().RequireAuthorization("ReadPolicy", "WritePolicy"); 
app.Run();
"AzureAd":
 {  
   "Instance":  "https://login.microsoftonline.com/",
   "ClientId":  "my_client_id",
   "ClientSecret":  "client_value",  
   "Domain":  "tenant_id",  
   "TenantId":  "tenant_id",  
   "Scopes":  "api://client_id/read    api://Client_id/write"  
}

有关更多信息,请参阅MSDoc1MSDoc2.

相关问题