gpt4 book ai didi

asp.net - 获取 ASP.NET 中 Azure AD 应用程序注册的所有 appRoles

转载 作者:行者123 更新时间:2023-12-03 04:53:03 32 4
gpt4 key购买 nike

在我的 ASP.NET MVC Core 项目中,我希望在应用程序注册中设置的所有 AppRoles 作为列表显示在我的 View 中。

目前我已尝试以下操作:

var servicePrincipal = await _graphServiceClient.Applications[_configuration["AzureAd:AppRegistrationId"]]
.Request()
.Select("appRoles")
.GetAsync();

我已向应用程序授予 API 权限 Application.Read.AllDirectory.Read.All,但我仍然收到错误:

ServiceException: Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation

问题:

  1. 我是否走在实现我想要的目标的正确道路上,只是缺少正确的许可?
    • 有人知道需要什么许可吗?
  2. 有其他方法可以完成此任务吗?
    • 我尝试从声明中获取角色,但这仅显示用户的角色,而不是应用注册中设置的所有角色

预先感谢您的帮助!

最佳答案

看来我来晚了...

我用委托(delegate)权限和应用程序权限进行了测试,都没有问题。

对于应用程序权限,使用如下代码很容易做到:

using Microsoft.Graph;
using Azure.Identity;

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantId ";
var clientId = "clientId ";
var clientSecret = "clientSecret ";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

var res = await graphClient.Applications["azure_ad_app_object_id_instead_of_client_id"].Request().GetAsync();
var roles = res.AppRoles;

这需要应用程序类型的 api 权限:

enter image description here

如果我们想使用委托(delegate)的api权限,由于这是一个MVC应用程序,我们需要首先将AAD身份验证集成到应用程序中。我们可以关注this sample 。一般来说,在program.cs中添加如下代码:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "TenantId",
"TenantId": "TenantId",
"ClientId": "ClientId",
"ClientSecret": "ClientSecret",
"CallbackPath": "/home", //don't forget to set redirect url in azure portal
"SignedOutCallbackPath ": "/signout-callback-oidc"
},

然后在代码中注入(inject)graphclient并使用它调用graph api,

private readonly GraphServiceClient _graphServiceClient;

public HomeController(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}

public async Task<IActionResult> IndexAsync() {
var b = await _graphServiceClient.Applications["aad_app_object_id"].Request().GetAsync();
return View();
}

enter image description here

关于asp.net - 获取 ASP.NET 中 Azure AD 应用程序注册的所有 appRoles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76425653/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com