开发者

user authentication withn OU using LDAP

开发者 https://www.devze.com 2023-04-13 07:40 出处:网络
I am trying to authenticate user using LDAP I am using this code: public bool IsAuthenticated(string domain, string username, string pwd)

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


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消