trying to get the data from active directory

Anjali Agarwal 1,366 Reputation points
2023-03-01T04:21:06.91+00:00

Hello,

I am trying to get the data from active directory. this is my code:

        UserPrincipal up = UserADIdentity.GetADUserInfo(WindowsIdentity.GetCurrent().Name.ToString());

public static UserPrincipal GetADUserInfo(string userName)

    {

        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))

        {

            UserPrincipal userPrincipal = new UserPrincipal(ctx);

            userPrincipal.SamAccountName = userName;

            userPrincipal.Enabled = true;

            userPrincipal = new PrincipalSearcher(userPrincipal).FindOne() as UserPrincipal;

          }

    }

Code works fine on my local computer, but when I deploy the code to IIS on server. This line of code:

WindowsIdentity.GetCurrent().Name.ToString()

is always returning NULL. I am not sure how to fix it. My code is running under applicationPoolIdentity. This is what i have in my startup.cs class:

       public void ConfigureServices(IServiceCollection services)
        {
         services.Configure<IISOptions>(options =>
            {
                options.AutomaticAuthentication= true;  

            });
 services.AddAuthentication(IISDefaults.AuthenticationScheme)

  .AddCookie(options =>
            {
                options.LoginPath = "/Home/Index";

            });


         }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,159 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
{count} votes