The C# LDAP Class uses the System.DirectoryServices namespace to perform Active Directory search. See the code below:
public bool IsAuthenticated(String domain, String username, String pwd)
{
//Create the directory entry
String domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
bool returnval = true;
ErrDesc = "";
try
{
//Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
//Search the user on the Active Directory
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
returnval = false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
returnval = false;
ErrDesc = "Error authenticating user. " + ex.Message;
}
return returnval;
}
IsAuthenticated function searches for a domain user inside a specific Domain. You just have to compile this class to build the DLL and call it from VB.NET or ASP.NET as shown below:
Imports SingleSignOnExt 'Import SingleSignOnExt.dll
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim son As New SingleSignOn()
son.LDAP_Path = "LDAP://yourdomain"
If son.IsAuthenticated("yourdomain", TextBox1.Text, TextBox2.Text) Then 'Parameters: Domain, Username, Password
Label1.Text = "User is authenticated!"
Else
Label1.Text = "User is invalid! -- " & son.ErrDesc
End If
End Sub
End Class
I also included a sample VB.NET project using the C# LDAP class. You can download it here.
3 comments:
is it necessary to develop this using the windows server or it will run on other os?
I haven't tried it yet but I can't see why it wont work as long as you are querying LDAP on Windows server.
thanks
we are also using LDAP server to authenticate users. If user password contains foreign characters it does not work. it throws an invalid password exception. but in other case it works fine.
Post a Comment