3

我正在尝试在 .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用它来验证客户端应用程序。我有第二个用户名和密码,username2需要password2在 LDAP 中检查才能登录。

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

4

2 回答 2

2

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

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;
}
于 2013-01-16T15:36:31.827 回答
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
于 2013-01-16T20:30:18.320 回答