gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:19:46 29 4
gpt4 key购买 nike

我使用 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
}
}

最佳答案

我花了过去 2 天的时间试图解决这个问题,终于搞定了。 Azure AD 是一个移动的目标,随着 ASPNETCORE 的成熟,大多数关于如何访问 Azure AD Graph 的文档已经过时。所以现在这就是您访问 Azure AD Graph 的方式。

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

然后您将使用上述信息生成访问 token ,然后使用该 token 调用图形。

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

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

关于c# - 在 asp.net 核心项目中获取 Azure Active Directory 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887685/

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