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

Kir*_*ran 29 c# azure-active-directory asp.net-core .net-core-rc2

我使用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?}");
});
Run Code Online (Sandbox Code Playgroud)

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

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();
}    
Run Code Online (Sandbox Code Playgroud)

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

{  
   "odata.error":{  
      "code":"Authentication_MissingOrMalformed",
      "message":{  
         "lang":"en",
         "value":"Access Token missing or malformed."
      },
      "values":null
   }
}
Run Code Online (Sandbox Code Playgroud)

Eas*_*vey 2

我花了两天时间试图解决这个问题,终于明白了。Azure AD 是一个不断变化的目标,随着 ASPNETCORE 的不断成熟,大多数有关如何访问 Azure AD Graph 的文档都已过时。现在,这就是您访问 Azure AD Graph 的方式。

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

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

\n\n
public async void GetUsers()\n    {\n        // Get OAuth token using client credentials \n        string tenantName = "your-tenant-name.onmicrosoft.com";\n        string authString = "https://login.microsoftonline.com/" + tenantName;\n        AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);\n        // Config for OAuth client credentials  \n        string clientId = "your-client-id";\n        string key = "your-AzureAD-App-Key";\n        ClientCredential clientCred = new ClientCredential(clientId, key);\n        string resource = "https://graph.windows.net";\n        AuthenticationResult authenticationResult;\n        try\n        {\n            authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCred);\n        }\n        catch(Exception ex)\n        {\n            throw new Exception(ex.Message, ex.InnerException);\n        }\n\n        var client = new HttpClient();\n        var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://graph.windows.net/your-tenant-name.onmicrosoft.com/users?api-version=1.6");\n        request.Headers.Authorization =\n          new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);\n        var response = await client.SendAsync(request);\n        var content = await response.Content.ReadAsStringAsync();\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

您可能会发现我遇到并且几个论坛正在讨论的另一个巨大问题是您是否收到 Authorization_Request_Denied 错误或 Insufficient_Permissions 错误。通过运行 PowerShell 命令以向您在 Azure AD 中注册的应用程序授予“管理员”权限,可以解决此问题。\n对 MS Graph API 的请求向我提供“授权请求被拒绝 - 权限不足,无法完成操作”

\n\n

您要运行的 powershell 命令是

\n\n
Connect-MsolService\n$ClientIdWebApp = \'{your_AD_application_client_id}\'\n$webApp = Get-MsolServicePrincipal \xe2\x80\x93AppPrincipalId $ClientIdWebApp\n#use Add-MsolRoleMember to add it to "Company Administrator" role).\nAdd-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

  • 好吧,我已经使用这些权限实现了这样一个应用程序。让主体成为可用的最高管理角色通常不是一个好主意。因为此时主体实际上可以重置任何用户的密码。 (2认同)