且构网

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

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

更新时间:2023-02-21 10:58:39

您需要为您的网站使用 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());
    }
  }
}