Microsoft Graph - GraphServiceClient 错误

Microsoft Graph - GraphServiceClient error

我正在尝试使用 Microsoft Graph api 从 Azure AD 获取用户成员。我有以下代码...

        {
            try
            {
                var credential = new ClientCredential(Settings.AzureADAuthenticationSettings.ClientId, Settings.AzureADAuthenticationSettings.ApplicationKey);
                var authContext = new AuthenticationContext(string.Format(Settings.AzureADAuthenticationSettings.AuthorityUrl, Settings.AzureADAuthenticationSettings.TenantId));
                var code = ValidationHelper.GetString(context.Request.Params["code"], string.Empty);
                var result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(context.Request.Url.GetLeftPart(UriPartial.Path)), credential, string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, ""));
                //var adClient = new ActiveDirectoryClient(new Uri(string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, result.TenantId)), async () => await GetAppTokenAsync(result.TenantId));
                var adClient = new GraphServiceClient(string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, result.TenantId),
                    new DelegateAuthenticationProvider(async requestMessage => {
                        var token = await GetAppTokenAsync(result.TenantId);
                        requestMessage.Headers.Authorization = new
                            AuthenticationHeaderValue("bearer", token);
                    }));
                //var adUser = (User) await adClient.Users.Request().Filter($"UserPrincipalName eq '{result.UserInfo.DisplayableId}'").Expand("MemberOf").GetAsync();
                var adUser = await adClient.Me.Request().Expand("MemberOf").GetAsync();

当最后一行执行时,出现以下错误:

Message: Method not found: 'System.Threading.Tasks.Task`1<!!0> Microsoft.Graph.BaseRequest.SendAsync(System.Object, System.Threading.CancellationToken, System.Net.Http.HttpCompletionOption)'.

Exception type: System.MissingMethodException
Stack trace:
at Microsoft.Graph.UserRequest.d__6.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Graph.UserRequest.GetAsync(CancellationToken cancellationToken)
at Microsoft.Graph.UserRequest.GetAsync()
at AzureADAuthentication.Handlers.AzureADAuthenticationHandler.d__0.MoveNext() in

如有任何帮助,我们将不胜感激!

请尝试使用

var members=graphClient.Me.MemberOf.Request().GetAsync().Result;

得到member of结果。

这是我的测试代码,我可以成功得到结果。

    IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
    .Create("e857b859-c5xxxf19-a819-27f03d2e047c")
    .WithTenantId("xxx.onmicrosoft.com")
    .WithDefaultRedirectUri()
    .Build();
    string[] scopes = { "User.ReadWrite.All" };
    InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopes);
    GraphServiceClient graphClient = new GraphServiceClient(authProvider);
    var members=graphClient.Me.MemberOf.Request().GetAsync().Result;

不是一个完整的答案,但是... 我遇到了同样的问题,大约在 System.Net.Http

我的开发环境中有一个可用的 Web 应用程序 (.net FW 4.7.2),但它无法在生产环境中运行(Azure 中的新虚拟机)- 恰好抛出此异常。

通过消除过程,我将 System.Net.HTTP 从 4.2 重定向到 4.0

    <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
    </dependentAssembly> 

我忍不住认为这会严重破坏其他东西,但它确实解决了这个问题。

好的,这就是我在不使用 .Me 属性的情况下解决问题的方法。

var credential = new ClientCredential(Settings.AzureADAuthenticationSettings.ClientId, Settings.AzureADAuthenticationSettings.ApplicationKey);
                    var authContext = new AuthenticationContext(string.Format(Settings.AzureADAuthenticationSettings.AuthorityUrl, Settings.AzureADAuthenticationSettings.TenantId));
                    var code = ValidationHelper.GetString(context.Request.Params["code"], string.Empty);
                    var result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(context.Request.Url.GetLeftPart(UriPartial.Path)), credential, string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, ""));
                    var adClient = new GraphServiceClient($"{Settings.AzureADAuthenticationSettings.GraphUrl}/v1.0/",
                        new DelegateAuthenticationProvider(async requestMessage =>
                        {
                            var token = await GetAppTokenAsync(result.TenantId);
                            requestMessage.Headers.Authorization = new
                                AuthenticationHeaderValue("bearer", token);
                        }));
                    var adUser = await adClient.Users[result.UserInfo.DisplayableId].Request().GetAsync();
                    var memberOf = await adClient.Users[adUser.Id].MemberOf.Request().GetAsync();

GetAppTokenAsync 是

private static async Task<string> GetAppTokenAsync(string tenantId)
        {
            var authenticationContext = new AuthenticationContext(string.Format(Settings.AzureADAuthenticationSettings.AuthorityUrl, tenantId), false);
            var clientCred = new ClientCredential(Settings.AzureADAuthenticationSettings.ClientId, Settings.AzureADAuthenticationSettings.ApplicationKey);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, ""), clientCred);

            return authenticationResult.AccessToken;
        }
var code = ValidationHelper.GetString(context.Request.Params["code"], string.Empty);
            var app = ConfidentialClientApplicationBuilder.Create(Settings.AzureADAuthenticationSettings.ClientId)
                .WithAuthority(string.Format(Settings.AzureADAuthenticationSettings.AuthorityUrl, Settings.AzureADAuthenticationSettings.TenantId))
                .WithClientSecret(Settings.AzureADAuthenticationSettings.ApplicationKey)
                .WithRedirectUri("http://localhost/AzureADAuthentication.axd").Build();
            var scopes = new[] { "User.Read", "Group.Read.All" };
            var result = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
            var adClient = new GraphServiceClient($"{Settings.AzureADAuthenticationSettings.GraphUrl}/v1.0/",
                new DelegateAuthenticationProvider(async requestMessage =>
                {
                    var token = result.AccessToken;
                    requestMessage.Headers.Authorization = new
                        AuthenticationHeaderValue("bearer", token);
                }));
            var adUser = await adClient.Me.Request().GetAsync();
            var memberOf = await adClient.Me.MemberOf.Request().GetAsync();