【问题标题】:Getting Azure Active Directory groups in asp.net core project在 asp.net 核心项目中获取 Azure Active Directory 组
【发布时间】:2023-04-02 12:48:01
【问题描述】:

我使用 Visual Studio 2015 创建了一个新项目,并启用了针对 Azure Active Directory 使用工作和学校帐户的身份验证。 下面是生成的配置函数的样子:

app.UseStaticFiles();
app.UseCookieAuthentication();
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
    ResponseType = OpenIdConnectResponseType.CodeIdToken
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

这是尝试获取用户组的基本操作代码:

public async Task<IActionResult> Index()
{
    var client = new HttpClient();
    var uri = "https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?api-version=1.6";

    var response = await client.GetAsync(uri);
    if (response.Content != null)
    {
        ViewData["response"] = await response.Content.ReadAsStringAsync();
    }

    return View();
}    

我需要使用或更改此代码以确保我可以获得用户组? 目前,响应是:

{  
   "odata.error":{  
      "code":"Authentication_MissingOrMalformed",
      "message":{  
         "lang":"en",
         "value":"Access Token missing or malformed."
      },
      "values":null
   }
}

【问题讨论】:

  • 嗨,Kiran,你对这个问题有什么了解吗?我有完全相同的问题。谢谢!
  • Kiran,如果你喜欢我的回答,请选择它。谢谢。
  • 检查您的索引方法,您正在创建一个 HttpClient() 实例并设置 URL。但是,您从未在调用 GetAsync() 之前设置授权标头。尝试阅读有关 UseOpenIdConnectAuthentication 的事件和 OnTokenValidated 方法的信息,这应该可以帮助您获取访问令牌并可以引导您找到解决方案。
  • 不确定这是否是您要查找的内容,但比使用 Graph IMO 获取角色和组要容易得多。我创建了一个使用 Azure AD 的 .Net Core 应用程序,该应用程序由现场公司 AD 提供。角色/用户可以在被推送到 Azure AD 的 AD 上进行管理,并且定义的应用角色是应用将使用的角色。 docs.microsoft.com/en-us/azure/architecture/…

标签: c# asp.net-core azure-active-directory .net-core-rc2


【解决方案1】:

我花了最后 2 天的时间试图解决这个问题,最终得到了它。 Azure AD 是一个不断变化的目标,ASPNETCORE 仍在成熟,大多数关于如何访问 Azure AD Graph 的文档已经过时。所以到目前为止,这就是您访问 Azure AD Graph 的方式。

  1. 记下您应用的 clientid
  2. 向 Azure Active Directory 注册您的应用
  3. 在该注册中生成一个密钥并记下它(您只能在它创建后立即查看)
  4. 记下您的“租户名称”(您也可以使用租户 ID)

然后您将使用上述信息生成访问令牌,然后使用该令牌调用 Graph。

public async void GetUsers()
    {
        // Get OAuth token using client credentials 
        string tenantName = "your-tenant-name.onmicrosoft.com";
        string authString = "https://login.microsoftonline.com/" + tenantName;
        AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
        // Config for OAuth client credentials  
        string clientId = "your-client-id";
        string key = "your-AzureAD-App-Key";
        ClientCredential clientCred = new ClientCredential(clientId, key);
        string resource = "https://graph.windows.net";
        AuthenticationResult authenticationResult;
        try
        {
            authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCred);
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message, ex.InnerException);
        }

        var client = new HttpClient();
        var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://graph.windows.net/your-tenant-name.onmicrosoft.com/users?api-version=1.6");
        request.Headers.Authorization =
          new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
        var response = await client.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
    }

您可能会发现我遇到并且多个论坛正在讨论的另一个重大问题是您是否收到 Authorization_Request_Denied 错误或 Insufficient_Permissions 错误。这可以通过运行 PowerShell 命令来解决,以授予您使用 Azure AD 注册的应用程序“管理员”权限。 Requests to MS Graph API gives me "Authorization Request Denied - Insufficient privileges to complete the operation"

你要运行的powershell命令是

Connect-MsolService
$ClientIdWebApp = '{your_AD_application_client_id}'
$webApp = Get-MsolServicePrincipal –AppPrincipalId $ClientIdWebApp
#use Add-MsolRoleMember to add it to "Company Administrator" role).
Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId

希望这会有所帮助。如果您认为需要进行任何精炼,请告诉我。

【讨论】:

  • 您不需要将服务主体添加到公司管理员角色。它只需要读取所有组委派权限/读取目录数据应用程序权限。如果您收到该错误,则表示未获得管理员同意或未请求许可。
  • 嗯.. 感谢 -1 @juunas。答案更多的是关于额外花絮之上的一切。与您上面的智慧相反,我给了应用程序“读取所有组委派权限/读取目录数据应用程序权限”,但它仍然没有足够的权限。只有在我应用了上面推荐的奖励解决方案之后,它才最终回复了我的请求。我希望我的回答对遇到同样问题的人有所帮助。
  • 好吧,我已经用这些权限实现了这样一个应用程序。让委托人成为可用的最高管理员角色通常不是一个好主意。因为此时委托人实际上可以重置任何用户的密码。
【解决方案2】:

Graph 客户端的代码更简单

var serviceRoot = new Uri(@"https://graph.windows.net/"+ tenantID);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
    () => Task.FromResult(authenticationResult.AccessToken));

// Fetch more user details from the Graph
var user = await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync();
// fetch all groups (DG + SG) and roles transitively for the user
var userGroups = await user.GetMemberObjectsAsync(securityEnabledOnly: false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多