具有来自Azure AD的承载令牌的安全ASP.Net Core 3.1 API

问题描述 投票:0回答:1

我有一个.net core 3.1 Web API。我想使用来自Azure AD的承载令牌来保护端点。

我关注了This guide。我已经为API注册了一个应用程序,为客户端注册了一个应用程序。

在我的API中,我为jwt添加了一个注册(如代码中所述)

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opt =>
    {
        opt.Audience = Configuration["AzureAd:ResourceId"];
        opt.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";
    });

而且我的API配置部分看起来像这样

"AzureAd": {
    "ResourceId": "api://<client-id-guid>",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "<tenant-id-guid>"
}

其中client-id-guid是api应用程序的客户端ID(使用api://地址的默认配置。)>

然后,对于我的客户,我在新解决方案中实施了一项测试,以获取令牌并调用安全的端点。

AadConfiguration config = AadConfiguration.ReadFromJsonFile("appsettings.json");

IConfidentialClientApplication app;

app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithClientSecret(config.ClientSecret)
    .WithAuthority(new Uri(config.Authority))
    .Build();

string[] ResourceIds = new string[] {config.ResourceID};

var token = await app.AcquireTokenForClient(ResourceIds)
    .ExecuteAsync();

Assert.IsFalse(string.IsNullOrWhiteSpace(token.AccessToken));

var request = new RestRequestBuilder("https://my-api-staging.azurewebsites.net/api")
    .WithSegments("health-check", "auth")
    .WithBearerToken(token.AccessToken)
    .Build();

try
{
    var response = await _restHelper.GetJsonAsync<dynamic>(request);

    Assert.IsFalse(string.IsNullOrEmpty(response?.serverTime?.ToString()));
}
catch (RestException e)
{
    Assert.IsFalse(true, e.ResponseContent);
}

以及此测试的配置

{
    "Instance": "https://login.microsoftonline.com/{0}",
    "TenantId": "<tenant-id-guid>",
    "ClientId": "<client-id-guid>",
    "ClientSecret": "<client-secret>",
    "ResourceId": "api://<api-client-id-guid>/.default"
}

Tenant ID是API和测试应用程序的销售

客户端ID是客户端应用程序注册的客户端ID及其秘密

资源ID是API的应用程序ID,它是api://和api的客户端ID

我可以很好地获取访问令牌。但是,当我使用获得的访问令牌调用端点时,出现以下错误:

在'CurrentUser \ My'上找不到主题为'CN = TODO.azurewebsites.net'的有效证书

我不确定执行文档中的步骤后,为什么身份验证失败。

我有一个.net core 3.1 Web API。我想使用来自Azure AD的承载令牌来保护端点。我遵循了本指南。我已经为API注册了一个应用程序,为客户端注册了一个应用程序。在...

c# security jwt azure-active-directory asp.net-core-3.1
1个回答
0
投票
我可以很好地获取访问令牌。但是,当我使用获得的访问令牌调用端点时,出现以下错误:
© www.soinside.com 2019 - 2024. All rights reserved.