Home > Back-end >  Microsoft Graph Api - request not working
Microsoft Graph Api - request not working

Time:06-15

I was trying to fetch users from an Azure Ad application. With some research I found how to do that. I realized that I needed an authentication provider, so I followed a this link that showed me how to choose the right one.

I tried with a client secret provider, but when I tried making a request using my GraphServiceClient, my program keeps closing with no errors. I tried different request like : await graphClient.Users.Request().GetAsync() or await graphClient.Me.Request().GetAsync(). Every time I make a request it fails.

I also tried using a Username/password provider with my credentials hard coded, but when I tried making a request my program closed again.

What am I doing wrong?

This is what I have right now:

        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };

        //var clientSecretCredential = new ClientSecretCredential(TenantId, ClientId, secret, options);

        var userName = "myUserName";
        var password = "myPassword";

        var creds = new UsernamePasswordCredential(userName, password, TenantId, ClientId, options);

        var graphClient = new GraphServiceClient(creds, scopes);

        try
        {
            var users = await graphClient.Users.Request().GetAsync();

            foreach (var user in users)
            {
                Debug.WriteLine(user.DisplayName);
            }
        }
        catch(Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }

CodePudding user response:

Please create a new asp.net core MVC project, then install Azure.Identity and Microsoft.Graph nuget package.

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var users = await graphClient.Users.Request().GetAsync();

CodePudding user response:

Found my problem!

It was regarding permissions, I added the wrong permissions. I added Delegated permissions, but I needed to add Application permissions. Since I wanted to see all users and groups I added those application permissions: Group.Read.All, GroupMember.Read.All and User.Read.All.

Thanks to @Tiny Wang, I knew that my error wasn't in the code, but elsewhere.

Edit

Forgot to say but I also changed await graphClient.Users.Request().GetAsync() to graphClient.Users.Request().GetAsync().Result to make it work.

  • Related