User validation with LDAP in C# (2005)


Once in my project I came to a problem where I need to validate a user with LDAP server. My project was in C# (2005). I have searched a lot in Google and at the end I got a working solution. There is another solution as well which does not worked for me but I guess for somebody else it might. So, I’ll present both of them here:

First the one which is widely used (but didn’t worked for me 😦 )

For this one you need to add a reference to System.DirectoryServices in your code.


public static bool ValidateUserCredentials(string _domain, string _userName, string _password)
{
DirectoryEntry nRoot = null;

try
{
nRoot = new DirectoryEntry("YOUR_LDAP_SERVER_PATH", _domain + "//" + _userName, _password);
//You can omit the domain if you want
nRoot.AuthenticationType = AuthenticationTypes.None;

Object obj = nRoot.NativeObject;

DirectorySearcher search = new DirectorySearcher(nRoot);

search.SearchScope = SearchScope.Subtree;
search.Filter = "(sAMAccountName=" + _userName + ")";
//You can specify the properties to Load
//search.PropertiesToLoad.Add("uid");

SearchResult _sr = search.FindOne();

if (null != _sr)
{
ResultPropertyCollection myResultPropColl = _sr.Properties;

foreach (string myKey in myResultPropColl.PropertyNames)
{
string tab = "    ";
Console.WriteLine(myKey + " = ");

foreach (Object myCollection in myResultPropColl[myKey])
{
string _val = tab + myCollection;
}
}
return true;
}
else
{
throw new Exception("User Not found");
}

}
catch (Exception _exp)
{
throw _exp;
}
finally
{
if (null != nRoot)
nRoot.Close();
}
}

And, following is the one worked for me.

For this one you need to add System.DirectoryServices.AccountManagement namespace in your reference.

 

public static bool ValidateUserCredentials(string _domain, string _userName, string _pwd)
{
try
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, _domain);

bool isValid = pc.ValidateCredentials(_userName, _pwd);
return isValid;

}
catch (Exception _Exp)
{
throw _Exp;
}
}

Don’t forget to tell me which one works for you 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s