使用C#在Active Directory上产生疑问

时间:2011-11-07 16:21:31

标签: c# active-directory

我有一个使用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;
    }

1 个答案:

答案 0 :(得分:1)

using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword")
}

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