Get Active Directory Information with ASP.NET with

2019-03-29 18:32发布

问题:

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.

回答1:

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());
    }
  }
}


回答2:

Hey this is rather a suggestion than answer to your question. Never ever will browsers allow you to bypass their security system. So the username and password box are unavoidable. What i would say is get the username,surname,and all that you want from the user and save it in a cookie that has really long expiry date. So the next time the user logs in, read that cookie and display what you want. Provide them with an option to change it if they want.

This is the best solution that should work most of the time.