c# - 守护进程应用程序和范围

标签 c# azure azure-active-directory azure-ad-msal

因此,我尝试看看是否可以支持 C# 守护程序应用程序可以访问受 MSAL.NET 和 OAuth2 范围保护的自定义 Web API 的场景。截至目前,我认为没有办法做到这一点。

库和工具集的版本是:

.NET Core 2.2 Microsoft.Identity.Client 4.1.0

客户是

var app = ConfidentialClientApplicationBuilder.Create("<client app id>")
                .WithClientSecret("<client_secret>")
                .WithAuthority("https://login.microsoftonline.com/<tenant_id_that_hosts_the_web_api>")
                .Build();

然后获取token

await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/.default" });

此时,我确实获得了 token ,我可以使用该 token 调用使用 MSAL 和具有上述应用 ID 的 Azure 应用程序保护的自定义 Web API 端点。这不起作用,因为我在端点上有基于策略的授权,期望在 Azure AD 应用程序中定义特定的自定义范围。

问题是,如何配置客户端和 Azure AD,以便获得作为 Web API 声明传入的特定范围?

最佳答案

您需要注册两个应用程序,一个用于守护程序应用程序(客户端应用程序),一个用于Web api(后端应用程序)。

enter image description here

单击 Web api 应用程序 -> 公开 API。 enter image description here

点击守护程序应用程序 -> API 权限 -> 添加权限 -> 我的 API -> 选择 Web api 应用程序 -> 选择权限。

enter image description here

然后是客户端

var app = ConfidentialClientApplicationBuilder.Create("<client app id>")
                .WithClientSecret("<client app client_secret>")
                .WithAuthority("https://login.microsoftonline.com/<tenant_id>")
                .Build();

范围:

await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/read" });

引用这个sample 。您可以将您的 Web API 视为 Microsoft Graph API。

关于c# - 守护进程应用程序和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57147646/

相关文章:

c# - 如何将两个查询的结果合并到 Elasticsearch 中的不同索引?

c# - 如何在 WPF 图像中显示位图

c# - 使用 AAD 应用程序访问 Microsoft Graph

azure - 使用服务主体的 oAuth token 进行身份验证会产生 "the audience is invalid"错误

C#控制位置精度

c# - ItemChecked 事件处理程序

azure - 如何使用 IdentityServer4 的 Azure 证书

Azure.Security.KeyVault.Secrets : az is not recognized as an internal or external command

Azure ADD 隐藏默认 URL 并使用 C# 显示所需 URL

azure - 无法使用 Microsoft graph API 获取照片