Home > Software design >  Get users contacts by Graph SDK
Get users contacts by Graph SDK

Time:01-16

I try to read all users contacts by using graph sdk and c# but in the user at the response always the array of contacts is null even though the user has contacts

I was requesting all user's contacts from exchange online with graph sdk and c#, but

var graphResult = graphClient.Users.Request().GetAsync().Result;
            Console.WriteLine(graphResult[0].Contacts[0]); 

returns NullReferenceException.

I granted following privileges:

privilidges

the following token is set in azure token

here you can see my tenant id and so on apid an so on tenent id

Main Class

using Microsoft.Graph;
using Azure.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using System.Data.SqlClient;

namespace ExchangeTestAppKonsole
{
    internal class Program
    {
        static void Main(string[] args)
        {

            getContacts();

            Console.ReadLine();
        }

        public static void getContacts()
        {
            var clientId = "de196208-b4d7-468f-8fa4-7328551566b9";
            var clientSecret = "~uG8Q~~vrTGuaIPfzeIR9GUUpSK5aaG.KZTYGcnD";
            var redirectUri = "https://global.consent.azure-apim.net/redirect";
            var authority = "https://login.microsoftonline.com/0be300e6-91fd-4638-bcd1-40d742ef6ece/v2.0";
            var cca = ConfidentialClientApplicationBuilder.Create(clientId)
                                                          .WithAuthority(authority)
                                                          .WithRedirectUri(redirectUri)
                                                          .WithClientSecret(clientSecret)
                                                          .Build();


            // use the default permissions assigned from within the Azure AD app registration portal
            List<string> scopes = new List<string>();
            scopes.Add("https://graph.microsoft.com/.default");

            var authenticationProvider = new MsalAuthenticationProvider(cca, scopes.ToArray());
            GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);

            var graphResult = graphClient.Users.Request().GetAsync().Result;
            Console.WriteLine(graphResult[0].Contacts[0]);
        }
    }
}

Authentication Provider

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ExchangeTestAppKonsole
{
    internal class MsalAuthenticationProvider : IAuthenticationProvider
    {
        private IConfidentialClientApplication _clientApplication;
        private string[] _scopes;

        public MsalAuthenticationProvider(IConfidentialClientApplication clientApplication, string[] scopes)
        {
            _clientApplication = clientApplication;
            _scopes = scopes;
        }

        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            var token = await GetTokenAsync();
            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
        }

        public async Task<string> GetTokenAsync()
        {
            AuthenticationResult authResult = null;
            authResult = await _clientApplication.AcquireTokenForClient(_scopes).ExecuteAsync();
            return authResult.AccessToken;
        }
    }
}

I also requested the contacts of the first user by logging in with this user into graphExplorer and requested the /me/contacts endpoint it shows 3 contacts

it seems to be a premissions thing but i've no idea what exactly the problem is.

CodePudding user response:

Contacts is a relationship on User resource type.

If you want to include some relationship in the response, you need to specify the relationship in Expand.

Not all relationships and resources support the expand. According to the documentation there is no mention that contacts supports expand, so probably this code won't work.

var graphResult = graphClient.Users
                   .Request()
                   .Expand("contacts")
                   .GetAsync().Result();
        Console.WriteLine(graphResult[0].Contacts[0]);

In that case you need to make a separate call for each user to get contacts.

var contacts = await graphClient.Users["{user_id}"].Contacts
    .Request()
    .GetAsync();

Users relationships

  • Related