1

I am trying to authenticate user using LDAP

I am using this code:

public bool IsAuthenticated(string domain, string username, string pwd)
{

DirectoryEntry nRoot = new DirectoryEntry("LDAP://192.134.1.142/dc=testDomain,dc=com");
nRoot.AuthenticationType = AuthenticationTypes.None;
nRoot.Username = "uid=username,dc=testDomain,DC=com";  //full dn
nRoot.Password = "pwd";

try
{ 
//Bind to the native AdsObject to force authentication.
Object obj = nRoot.NativeObject;

DirectorySearcher search = new DirectorySearcher(nRoot);

search.SearchScope = SearchScope.Subtree;
search.Filter = "uid=username";               
search.PropertiesToLoad.Add("uid");

SearchResult sr = search.FindOne();
if(null == sr )
{
  return false;
}
// Update the new path to the user in the directory
_path = sr.Path;
_filterAttribute = (String)result.Properties["uid"][0];
  }
 catch (Exception ex)
 {
 throw new Exception("Error authenticating user. " + ex.Message);
 }
 return true;
 }

Here if the user is not a part of any OU the code runs fine but if it is a part of an OU it won't work and ii get an error

System.Runtime.InteropServices.COMException at
// Bind to the native AdsObject to force authentication. Object obj = nRoot.NativeObject;

How do I get the user validated belonging to an OU or any other group??

I tried hard coding the OU to and it worked, but i cannot ask a user to enter his OU

 nRoot.Username = "uid=username,ou=test,dc=testDomain,DC=com";  //full dn
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user175084
  • 4,550
  • 28
  • 114
  • 169
  • 1
    See my answer to this question: http://stackoverflow.com/questions/290548/c-sharp-validate-a-username-and-password-against-active-directory/499716#499716 - does that help?? – marc_s Oct 14 '11 at 20:35

2 Answers2

1
string ldapsrv = "mydomain.com:389";
string dc_oq = "OU=domain_app_auth,DC=domain,DC=uk,DC=com";//,
user_nme = "username";
pws = "password";

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapsrv, dc_oq, ContextOptions.Negotiate | ContextOptions.Negotiate))
{
    isValid = pc.ValidateCredentials(user_nme, pws);
}
0

You need to take the username, find the object whose uid=username, and then read the distinguishedName attribute or else the name of the returned object (which will be the full DN) and log in with that discovered full DN.

geoffc
  • 4,030
  • 7
  • 44
  • 51