简体   繁体   中英

Microsoft Graph - GraphServiceClient error

I'm trying to get a users member of from Azure AD using Microsoft Graph's api. I have the following code...

        {
            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();

When the last line executes, I get the following error:

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

Any help would be much appreciated!

Please try to use

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

to get the member of result.

Here is my testing code, I can get the result successfully.

    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;

在此处输入图像描述

Not really a complete answer, but... I had the same problem and it's around System.Net.Http

I had a working webapp (.net FW 4.7.2) in my dev env, but it would not work in prod (a newish VM in azure) - throwing exactly this exception.

By a process of elimination, I got to redirecting System.Net.HTTP from 4.2 to 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> 

I can't help but think that this is going to break something else horribly, but it does fix exactly this problem.

Ok so here is what I did to resolve the issue without using the.Me attributes.

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();

The GetAppTokenAsync is

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM