【问题标题】:doubts at Active Directory using C#使用 C# 对 Active Directory 的疑问
【发布时间】:2011-11-07 16:21:30
【问题描述】:

我有一个使用 Active Directory 的 Web 应用程序。 我在参数(用户、密码和自己的域)中创建了一个执行身份验证域的函数。 在确定行显示一条消息“未指定的错误”,如下所示:

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.
           ---> This Line occurred error
             **object obj = entry.NativeObject;** 
           ---> Line Above occurred error

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

【问题讨论】:

  • System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) 中未指定错误
  • 从不throw new Exception("Error authenticating user. " + ex.Message)总是throw new Exception("Error authenticating user.", ex)。这样,您就不会丢失包装异常的堆栈跟踪信息。
  • 这似乎是一种冗长的做法,而且有点不必要。您是否只是尝试使用用户名和密码针对 AD 域对用户进行身份验证?如果你是你只需要一个“PrincipleContext”对象
  • 那么异常类型是什么?
  • 我需要在客户端服务器上进行身份验证,我目前正在尝试使用 IP 127.0.0.1 在我自己的机器上进行身份验证

标签: c# active-directory


【解决方案1】:
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword")
}

这可能会更好地满足您的需求。您至少需要 .NET3.5,并且应该使用它来进行身份验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多