.net core 如何为GraphServiceClient设置资源URL以获取组?

.net core 如何为GraphServiceClient设置资源URL以获取组?,.net-core,azure-active-directory,microsoft-graph-api,azure-ad-graph-api,.net Core,Azure Active Directory,Microsoft Graph Api,Azure Ad Graph Api,我正在尝试使用从中的\u claims\u sources接收的groups:src1端点值从Graph API获取广告组 我的客户端正在使用客户端凭据,可以获取广告中所有用户和组的信息 我是这样设置的: private async Task<IList<Group>> GetUserGroupsAsync(string endpoint) { // Endpoint is from the claims in a previous OIDC request

我正在尝试使用从中的
\u claims\u sources
接收的
groups:src1
端点值从Graph API获取广告组

我的客户端正在使用客户端凭据,可以获取广告中所有用户和组的信息

我是这样设置的:

private async Task<IList<Group>> GetUserGroupsAsync(string endpoint)
{
    // Endpoint is from the claims in a previous OIDC request

    // Setup a client if it does not exist
    PrepareGraphApiClient();

    // I can fetch my groups using the methods in the client
    // var groupPage = await graphServiceClient.Me.MemberOf.Request().GetAsync();

    // This is where I would like to use the resource URL received from the
    // claims I receive in a previous OIDC request
    var groupPageFromUrl = ???

    ...
}

private void PrepareGraphApiClient()
{
    if (graphServiceClient != null) return;

    try
    {
        AuthenticationContext authority = new AuthenticationContext(oidcOptions.Authority);
        ClientCredential clientCredential = new ClientCredential(oidcOptions.ClientId, oidcOptions.ClientSecret);

        var graphApiResource = "https://graph.microsoft.com";
        AuthenticationResult authenticationResult = authority.AcquireTokenAsync(graphApiResource, clientCredential).Result;

        graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(
            async requestMessage =>
            {
                // Add token to outgoing requests
                requestMessage.Headers.Authorization =
                    new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
            }));
    }
    catch (Exception ex)
    {
        logger.LogDebug($"Could not create the graph client {ex}");
        throw;
    }
}
专用异步任务GetUserGroupsAsync(字符串端点)
{
//端点来自上一个OIDC请求中的声明
//如果客户端不存在,请设置客户端
PrepareGraphicClient();
//我可以使用客户端中的方法获取我的组
//var groupPage=await graphServiceClient.Me.MemberOf.Request().GetAsync();
//这是我想使用从
//我在以前的OIDC请求中收到的索赔
var groupPageFromUrl=???
...
}
私有无效预处理许可权()
{
if(graphServiceClient!=null)返回;
尝试
{
AuthenticationContext authority=新的AuthenticationContext(oidcOptions.authority);
ClientCredential ClientCredential=新的ClientCredential(oidcOptions.ClientId,oidcOptions.ClientSecret);
var graphApiResource=”https://graph.microsoft.com";
AuthenticationResult AuthenticationResult=authority.AcquireTokenAsync(graphApiResource,clientCredential).Result;
graphServiceClient=新graphServiceClient(新DelegateAuthenticationProvider(
异步请求消息=>
{
//向传出请求添加令牌
requestMessage.Headers.Authorization=
新的AuthenticationHeaderValue(“承载者”,authenticationResult.AccessToken);
}));
}
捕获(例外情况除外)
{
logger.LogDebug($“无法创建图形客户端{ex}”);
投掷;
}
}

我可以使用GraphServiceClient声明中的资源URL吗?或者我必须设置一个HttpClient来发出请求吗?

\u claim\u sources.src1
中标识的端点用于Azure AD Graph,因此您使用的令牌需要用于Azure AD Graph API(
https://graph.windows.net
),不适用于Microsoft Graph(
https://graph.microsoft.com
)。这也意味着您不能使用Microsoft Graph SDK,因为API请求和响应根本不同

您有两个选择:

  • (建议)使用端点仅作为必须执行查找的指示,并使用Microsoft Graph SDK对Microsoft Graph进行等效调用:

    var memberOfIds=await graphServiceClient
    .Users[userObjectId]#来自访问令牌中的“oid”
    .GetMemberObjects(securityEnabledOnly:true)#如果groupMembershipClaims为“SecurityGroup”,则为true;如果为“All”,则为false
    .Request()
    .PostAsync();
    
  • 使用给定的端点,并使用(例如)HttpClient构建您自己对Microsoft Graph的请求。一个快速的“n”脏示例:

    使用(var-client=new-HttpClient())
    {
    #在你使用代币之前,一定要把它拿对。阿达尔会负责买一个新的
    #如果需要,或者使用现有的缓存令牌(如果不需要)。
    authenticationResult=
    authority.AcquireTokenAsync(“https://graph.windows.net“,客户端凭据)
    client.DefaultRequestHeaders.Authorization=
    新的AuthenticationHeaderValue(“承载者”,authResult.AccessToken);
    #向Azure AD Graph发出API请求。注意,我们必须包括API版本和
    #请求机构。
    HttpResponseMessage response=wait client.PostAsync(
    $“{src}?api版本=1.6”,新的StringContent(
    “{'securityEnabledOnly':true}”,如果GroupMembershipClaimes为“SecurityGroup”,则为true,如果为“All”,则为false
    UnicodeEncode.UTF8,
    “应用程序/json”);
    if(响应。IsSuccessStatusCode)
    {
    #注意,我们正在进行反序列化,就像它是对getMemberObjects的Microsoft Graph响应一样,
    #而不是Azure广告图响应。虽然它可以工作,但这有点风险,而且
    #更正确的做法是明确定义Azure广告图响应的形式。
    var memberOfIds=JsonConvert.DeserializeObject(
    wait response.Content.ReadAsStringAsync()).Value;
    }
    }
    
  • 作为旁注,我注意到您有权在您提供给Microsoft Graph library的
    DelegateAuthenticationProvider
    之外获取令牌。您应该将
    AcquireTokenAsync
    调用放在内部,以便它为每个Microsoft Graph请求检索新令牌。库(ADAL)将负责使用缓存的令牌(如果有可用的令牌),或发出新的令牌请求(如果没有可用的令牌或可用的令牌已过期)。类似如下:

    graphServiceClient=new graphServiceClient(new DelegateAuthenticationProvider(
    异步请求消息=>
    {
    //获得新的代币
    AuthenticationResult AuthenticationResult=
    wait authority.AcquireTokenAsync(GraphPaireSource、clientCredential);
    //向传出请求添加令牌
    requestMessage.Headers.Authorization=
    新的AuthenticationHeaderValue(“承载者”,authenticationResult.AccessToken);
    }));
    
    这是一个很好的答案,谢谢!我真想知道为什么
    securityenably
    标志在#1中为假,而在#2中为真?我目前正在尝试类似的方法:
    var-groupPage=wait-graphServiceClient.Users[oid].GetMemberGroups(true.Request()…PostAsync();
    检索用户所属的组。因为我刚刚创建了这些组。实际值应取决于您在应用程序清单中将
    groupmembershipClaimes
    设置为什么。如果是“SecurityGroup”,则应使用
    true
    。如果是“All”,则应使用
    false
    (我将进行编辑以确保一致性)。