Get Active Directory Information with ASP.NET without username and password

15,371

you need to use Windows authentication mode for your website.

<system.web>
    <authentication mode="Windows" />
    <authorization>
        <deny users="?" /> <!-- disable anonymous authentication -->
    </authorization>
</system.web>

... and then use LDAP query under current user's context to get extended information about the user:

using System.DirectoryServices;

using (var de = new DirectoryEntry("LDAP://DC=MYDOMAIN,DC=COM"))
using (var ds = new DirectorySearcher(de))
{
  ds.Filter = string.Format("(sAMAccountName={0})", HttpContext.Current.User.Identity.Name);
  ds.PropertiesToLoad.AddRange(new [] {
            "sn",  // last name
            "givenName",  // first name
            "mail",  // email
            "telephoneNumber",  // phone number
            // etc - add other properties you need
            });
  var res = ds.FindOne();

  foreach (string propName in res.Properties.PropertyNames)
  {
    ResultPropertyValueCollection valueCollection = res.Properties[propName];
    foreach (Object propertyValue in valueCollection)
    {
         Console.WriteLine("Property: " + propName + ": " + propertyValue.ToString());
    }
  }
}
Share:
15,371
qods
Author by

qods

Updated on June 10, 2022

Comments

  • qods
    qods almost 2 years

    I am trying to get users' Active Directory information on the local network, from an ASP.NET Web Application. The Web Application is running on an IIS on the local network.

    What I want: When users log into the website, they can see their name, surname, username, email and picture from Active Directory. The problem is, when they enter their website, the web application is asking for username and password. Users have already entered their username and password when turning on their PCs. So they shouldn't need to do it again.

    Users login to PCs with their username and password. I can get domain and username with:

    string adInfo = Request.ServerVariables["LOGON_USER"];
    

    Also I can get Active Directory info on my local PC on debug when testing System.DirectoryServices, but when other users try this web app in local, the username and password dialog appears.

    How can I make it so that users are able to enter their website without entering their username and password?

    I tried all samples here, but I can not find any solution. I think I am missing some important things.

  • Mike Beeler
    Mike Beeler over 10 years
    This assumes that the current user has read access to active directory, not all installations allow this, you may have to consider running your app pool with a service account that Is either in the domain admin group or similar to provide access. This needs do be done carefully for obvious security reasons