繁体   English   中英

在asp.net核心项目中获取Azure Active Directory组

[英]Getting Azure Active Directory groups in asp.net core project

我使用Visual Studio 2015创建了一个新项目,并使用Azure Active Directory的工作和学校帐户启用了身份验证。 以下是生成的configure函数的外观:

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
   }
}

我花了最近两天的时间试图解决这个问题并最终得到它。 Azure AD是一个移动目标,ASPNETCORE仍然成熟,大多数有关如何访问Azure AD Graph的文档已经过时。 到目前为止,您将如何访问Azure AD Graph。

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

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

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“管理员”权限的应用程序解决此问题。 对MS Graph API的请求给了我“拒绝授权请求 - 没有足够的权限来完成操作”

您要运行的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

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

使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM