且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用ASP.NET无需用户名和密码即可获取Active Directory信息

更新时间:2023-02-21 10:46:23

您需要对网站使用 Windows 身份验证模式.

you need to use Windows authentication mode for your website.

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

...,然后在当前用户的上下文下使用LDAP查询以获取有关该用户的扩展信息:

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