日期:2014-05-17  浏览次数:21334 次

从 ASP .NET 进行 Active Directory 域服务身份验证
从 ASP .NET 进行 Active Directory 域服务身份验证
本主题说明 ASP.NET 应用程序如何使用 Forms 身份验证来允许用户使用轻型目录访问协议 (LDAP) 对 Active Directory 域服务进行身份验证。在对用户进行身份验证和重定向后,可以使用 Global.asax 文件的 Application_AuthenticateRequest 方法在 HttpContext.User 属性中存储 GenericPrincipal 对象(该对象贯穿整个请求)。

创建新的 ASP.NET Web 应用程序
启动 Microsoft Visual Studio .NET。

在“文件”菜单上,指向“新建”,然后单击“项目”。

在“项目类型”下,单击“Visual C# 项目”,然后在“模板”下单击“ASP.NET Web 应用程序”。

在“名称”框中,键入 FormsAuthAd。

如果您使用的是本地服务器,则在“服务器”框中保留默认的 http://localhost。否则,添加指向您所用服务器的路径。单击“确定”。

在“解决方案资源管理器”中,右键单击“引用”节点,然后单击“添加引用”。

在“添加引用”对话框中的 .NET 选项卡上,依次单击 System.DirectoryServices.dll、“选择”和“确定”。

添加 System.DirectoryServices 身份验证代码
在“解决方案资源管理器”中,右键单击项目节点,指向“添加”,然后单击“添加新项”。

在“模板”下,单击“类”。

在“名称”框中键入 LdapAuthentication.cs,然后单击“打开”。

用下面的代码替换 LdapAuthentication.cs 文件中的现有代码:

using System;
using System.Text;
using System.Collections;
using System.Web.Security;

using System.Security.Principal;   
using System.DirectoryServices;


namespace FormsAuth
{
  public class LdapAuthentication
  {
    private string _path;
    private string _filterAttribute;

    public LdapAuthentication(string path)
    {
      _path = path;
    }

    public bool IsAuthenticated(string domain, string username, string pwd)
    {
      string domainAndUsername = domain + @"/" + username;
      DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

      try
      {
        //Bind to the native AdsObject to force authentication.
        object obj = entry.NativeObject;

        DirectorySearcher search = new DirectorySearcher(entry);

        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();

        if(null == result)
        {
          return false;
        }

        //Update the new path to the user in the directory.
        _path = result.Path;
        _filterAttribute = (string)result.Properties["cn"][0];
      }
      catch (Exception ex)
      {
        throw new Exception("Error authenticating user. " + ex.Message);
      }

      return true;
    }

    public string GetGroups()
    {
      DirectorySearcher search = new DirectorySearcher(_path);
      search.Filter = "(cn=" + _filterAttribute + ")";
      search.PropertiesToLoad.Add("memberOf");
      StringBuilder groupNames = new StringBuilder();

      try
      {
        SearchResult result = sea