Free Information Technology Magazines and eBooks

Tuesday, April 21, 2009

.NET LDAP Authentication

One type of authentication that we can use on our application is using the Windows Domain Account Authentication which we can achieve by using Lightweight Directory Access Protocol. On my previous project, we used an LDAP C# class to implement a Single Sign-On authentication. Single Sign-On means that all applications either web or desktop shares a single database of user accounts and that is the active directory users. To employ LDAP authentication on your own project, just download the complete C# class at mediafire.


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:

Anonymous said...

is it necessary to develop this using the windows server or it will run on other os?

Fryan Valdez said...

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

aspnetfeature said...

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.