Home > Blockchain >  azure ad get all users using graph api
azure ad get all users using graph api

Time:05-23

I tested to get all users information in C# and Postman using graph API.

In postman, It correctly responded. But, In c#, It just responded sign in user.

This is a method in c# and postman

GET https://graph.microsoft.com/v1.0/users
// Load configuration settings from PrivateSettings.config
private static string appId = ConfigurationManager.AppSettings["ida:AppId"];
private static string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private static List<string> graphScopes =
            new List<string>(ConfigurationManager.AppSettings["ida:AppScopes"].Split(' '));

// Returns all of the users in the directory of the signed-in user's tenant. 
public static async Task<IGraphServiceUsersCollectionPage> GetUsersAsync()
{
    IGraphServiceUsersCollectionPage users = null;

    try
    {
        var graphClient = GetAuthenticatedClient();
        users = await graphClient.Users.Request().GetAsync();
        foreach (var user in users)
        {
            Debug.WriteLine("User: "   user.DisplayName);
        }
        return users;
    }
    catch (ServiceException e)
    {
        Debug.WriteLine("We could not get users: "   e.Error.Message);
        return null;
    }
}

private static GraphServiceClient GetAuthenticatedClient()
{
    return new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                            .WithRedirectUri(redirectUri)
                            .WithClientSecret(appSecret)
                            .Build();

                        var tokenStore = new SessionTokenStore(idClient.UserTokenCache,
                                HttpContext.Current, ClaimsPrincipal.Current);

                        var userUniqueId = tokenStore.GetUsersUniqueId(ClaimsPrincipal.Current);
                        var account = await idClient.GetAccountAsync(userUniqueId);

                // By calling this here, the token can be refreshed
                // if it's expired right before the Graph call is made
                var result = await idClient.AcquireTokenSilent(graphScopes, account)
                            .ExecuteAsync();

                        requestMessage.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    }));
        }

enter image description here enter image description here

CodePudding user response:

In the call from Postman did you use the same token used in code call? Maybe there are different users with different permissions?

  • Related