【问题标题】:Which is the correct flow to get current user's groups from Microsoft graph?从 Microsoft graph 获取当前用户组的正确流程是什么?
【发布时间】:2020-01-18 12:15:40
【问题描述】:

您好,我正在对我的 web api 实施基于组的授权。我有客户端应用程序招摇。通过 swagger 我正在登录并调用 web api。在 web api 中,我想通过 Microsoft graph 实现基于组的授权。当我通过 swagger 登录时,我将获得一个令牌,并且我正在传递给我的 webapi。如果我没记错的话,现在我需要一个令牌来调用 Microsoft graph。那么我可以使用相同的令牌来调用 microsoft graph 吗?我混淆了自己并实施了客户凭证流程。客户端凭证流将获取应用的令牌(此处用户登录令牌无关)。

   public static async Task<GraphServiceClient> GetGraphServiceClient()
        {
            // Get Access Token and Microsoft Graph Client using access token and microsoft graph v1.0 endpoint
            var delegateAuthProvider = await GetAuthProvider();
            // Initializing the GraphServiceClient
            graphClient = new GraphServiceClient(graphAPIEndpoint, delegateAuthProvider);

            return graphClient;
        }


        private static async Task<IAuthenticationProvider> GetAuthProvider()
        {
            AuthenticationContext authenticationContext = new AuthenticationContext(authority);
            ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

            // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResource, clientCred).ConfigureAwait(false);
            var token = authenticationResult.AccessToken;

            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
                return Task.FromResult(0);
            });

            return delegateAuthProvider;
        }

以下代码将返回所有组。

GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
 var groupList = await client.Groups.Request().GetAsync();

但我的要求是获取当前登录的用户组。那么有人可以帮助我应该使用哪个流程并且仅在上面的代码中是否可以获得当前用户组?有人可以帮助我理解这些并正确实施吗?任何帮助将不胜感激。谢谢

【问题讨论】:

  • 你有机会看看我的回答吗?有更新吗?

标签: asp.net-core azure-active-directory microsoft-graph-api


【解决方案1】:

正如我们之前所讨论的,您应该从您的 webapi 应用程序调用 Microsoft Graph API。

因此,您不应使用相同的访问令牌来调用 Microsoft Graph。当您向 Microsoft Graph 请求新的访问令牌时,应将 Microsoft Graph 端点 (https://graph.microsoft.com) 指定为资源。

其次,客户端凭据流意味着仅限应用程序的权限(无用户)。那么如果没有登录用户,我们如何获取用户组呢?

您应该考虑使用AcquireTokenAsync(String, ClientAssertion, UserAssertion)

之后,使用以下代码获取已登录用户的组。

GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
var memberOf = await graphClient.Me.MemberOf.Request().GetAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多