AllTech
AllTech

Reputation: 603

Exception in Query Azure Active AD users using C# code

I have registered an app in Azure Active Diretcory and using below code:

<appSettings>
    <add key="TenantId" value="b1f9cb25-7c7a-4ecd-96c1-513c2b42c350"/>
    <add key="TenantName" value="myTentantName.onmicrosoft.com"/>
    <add key="ClientId" value="d82c0c6a-8c14-4c42-8aca-60c79fcfc9b4"/>
    <add key="ClientSecret" value="27?_MOh_qM633Hcccct;cw:@*$9ojcsNxve)rYI"/>
</appSettings>

internal class Settings
{
    public const string ResourceUrl = "https://graph.microsoft.com";
    public static string TenantId => ConfigurationManager.AppSettings["TenantId"];
    public static string TenantName => ConfigurationManager.AppSettings["TenantName"];
    public static string ClientId => ConfigurationManager.AppSettings["ClientId"];
    public static string ClientSecret => ConfigurationManager.AppSettings["ClientSecret"];
    public static string AuthString => "https://login.microsoftonline.com/" + TenantName; 
}

class AuthenticationHelper

public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication()
{
    Uri servicePointUri = new Uri(Settings.ResourceUrl);
    Uri serviceRoot = new Uri(servicePointUri, Settings.TenantId);
    ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(
        serviceRoot,
        async () => await AcquireTokenAsyncForApplication());
    return activeDirectoryClient;
}

private static async Task<string> AcquireTokenAsyncForApplication()
{
    AuthenticationContext authenticationContext = new AuthenticationContext(Settings.AuthString, false);

    ClientCredential clientCred = new ClientCredential(Settings.ClientId, Settings.ClientSecret);
    AuthenticationResult authenticationResult =
        await authenticationContext.AcquireTokenAsync(
            Settings.ResourceUrl,
            clientCred);
    string token = authenticationResult.AccessToken;
    return token;
}

main class

var client = AuthenticationHelper.GetActiveDirectoryClientAsApplication();

try
{
    var users = await client.Users.OrderBy(user => user.DisplayName).ExecuteAsync();
    var foundUser = await client.Users.Where(user => user.ObjectId == "d62d8c6a-dc69-46c1-99c4-36cd672f0c12").ExecuteAsync();
    foreach (var user in users.CurrentPage)
    {
        Console.WriteLine(user.DisplayName + " " + user.ObjectId);
    }
}
catch (Exception exception)
{
    Console.WriteLine(exception);
}

I am getting an error in main class in line :

var users = await client.Users.OrderBy(user => user.DisplayName).ExecuteAsync();

System.InvalidOperationException: An error occurred while processing this request. ---> System.PlatformNotSupportedException: Secure binary serialization is not supported on this platform.

enter image description here

Upvotes: 0

Views: 418

Answers (2)

AlfredoRevilla-MSFT
AlfredoRevilla-MSFT

Reputation: 3485

Now that the wrong resource issue was spotted code works well (I tested it myself). What are the remaining issues?

  • Specified file name is too long? This is due Windows Maximum Path Length Limitation. Move your repo files up the closest to your drive or root folder path.
  • AADSTS90002? Try using the tenand Id instead of the full name.
  • Authorization_RequestDenied is due lack of permissions, ensure you're setting and consenting the required ones, for your code you need https://graph.windows.net/Directory.Read.All. Finally you can get users with both AAD Graph API and MS Graph API. The recommendation is to move to the later since the former is going to be deprecated. Take a look to Migrate Azure AD Graph apps to Microsoft Graph.

Upvotes: 1

Jack Jia
Jack Jia

Reputation: 5549

I got a success by referring to the official sample: Azure-Samples / active-directory-dotnet-graphapi-console

enter image description here

The only difference is that the ResourceUrl is not https://graph.microsoft.com. The correct value is https://graph.windows.net.

That makes sense. Because you are trying to use AD Graph not Microsoft Graph


Update

As in the code, you are acquiring the token with client credential. So, the token you get only has application permission. So, you need to add and grant application permission in Azure portal:

enter image description here

Upvotes: 1

Related Questions