如何在LDAP中进行身份验证?

时间:2013-01-16 14:48:07

标签: c# .net active-directory ldap

我正在尝试用.NET中的LDAP创建一个简单的身份验证系统。 我正在检查.NET中的一些命名空间,并简单地制作如下的标准代码段。

DirectoryEntry de = new DirectoryEntry(path,username,password);

DirectorySearcher s = new DirectorySearcher(de);
s.Filter = "(&(cn=" + username2 + "))";

SearchResult result = s.FindOne();
if (result != null) {
    Console.WriteLine("User exists");
} else {
    Console.WriteLine("User does not exist");
}

我有一个管理员用户名和密码usernamepassword,我用它来验证客户端应用程序。我有第二个用户名和密码,username2password2需要在LDAP中进行检查才能登录。

username是管理员帐户,username2只是LDAP中的用户。那么如何查看username2的密码?

2 个答案:

答案 0 :(得分:1)

稍微向后(和笨重)的方式是以用户身份登录并尝试检索某些内容,然后将异常视为无效密码:

static bool CheckUser(string userName, string password) 
{
    var adSettings = ConfigurationManager.ConnectionStrings["ActiveDirectory"];
    if (adSettings == null ||
        string.IsNullOrWhiteSpace(adSettings.ConnectionString))
    {
        return false;
    }

    try
    {
        using (var de = new DirectoryEntry(adSettings.ConnectionString, userName, password))
        {
            // This should throw an exception if the password is wrong
            object nativeObject = de.NativeObject;
        }
    }
    catch (DirectoryServicesCOMException)
    {
        // Wrong password
        return false;
    }
    catch (System.Runtime.InteropServices.COMException)
    {
        // Can't connect
        return false;
    }

    return true;
}

答案 1 :(得分:0)

我在VB中有一些东西可能会帮助我猜测。几天前与我的同事一起工作。请让我知道--- 代码:

    Dim cookie As HttpCookie = New HttpCookie("username")
    cookie.Value = TextBox1.Text
    cookie.Expires = DateAndTime.Now.AddHours(12)
    Response.Cookies.Add(cookie)
    Dim entry As New DirectoryEntry("LDAP://xyz.com/dc=xyz,dc=com", TextBox1.Text, TextBox2.Text)
    Try
        Dim obj As New Object
        obj = entry.NativeObject
        Dim search As New DirectorySearcher(entry)
        search.Filter = "(SAMAccountName=" + TextBox1.Text + ")"
        search.PropertiesToLoad.Add("cn")
        Dim result As SearchResult
        result = search.FindOne()
        If result.Equals(Nothing) then
            MsgBox("Try Again with valid username")
        Else
            MsgBox("User Found!")
        Response.Redirect("~/Dashboard.aspx")
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

End Sub