views:

358

answers:

2

I'm using DirectoryServices to authenticate a user against an ADLDS (the lighteweight Active Directory). After I pass authentication. How can I determine the DN or SID of the currently logged in user?

using (DirectoryEntry entry = new DirectoryEntry(<a>LDAP://XYZ:389</a>,
userName.ToString(),
password.ToString(),
AuthenticationTypes.Secure))
{
try
{
// Bind to the native object to force authentication to happen
Object native = entry.NativeObject;
MessageBox.Show("User authenticated!");
}
catch (Exception ex)
{
throw new Exception("User not authenticated: " + ex.Message);
}
...

Thanks

+1  A: 

To my knowledge you will have to do an LDAP Search for the user and get the distinguishedName property from AD. See below:

// you can use any root DN here that you want provided your credentials
// have search rights
DirectoryEntry searchEntry = new DirectoryEntry("LDAP://XYZ:389");

DirectorySearcher search = new DirectorySearcher(searchEntry);
search.Filter = "(&(objectclass=user)(objectCategory=person)" +
  "(sAMAccountName=" + userName + "))";    

if (search != null)
{
  search.PropertiesToLoad.Add("sAMAccountName");
  search.PropertiesToLoad.Add("cn");
  search.PropertiesToLoad.Add("distinguishedName");

  log.Info("Searching for attributes");

  // find firest result
  SearchResult searchResult = null;
  using (SearchResultCollection src = search .FindAll())
  {
 if (src.Count > 0)
   result = src[0];
  }

  if (searchResult != null)
  {
    // Get DN here
    string DN = searchResult.Properties["distinguishedName"].ToString();
  }
mjmarsh
mjmarsh Thanks ~ but I get an exception at src = search.FindAll()There is no such object on the server.------I realized the user logging in has a class type "foreignSecurityPrincipal" in the Active Directory lightweight so I figured perhaps I can just modify your filter to be:search.Filter = "(But that gave me the same exception. Any idea what I am missing? I feel like your code is getting me very close to what I need.
sOltan
+1  A: 

Thanks ~ but I get an exception at

src = search.FindAll() 
There is no such object on the server.

I realized the user logging in has a class type "foreignSecurityPrincipal" in the Active Directory lightweight so I figured perhaps I can just modify your filter to be:

search.Filter = "(&(objectclass=foreignSecurityPrincipal)" + "(sAMAccountName=" + userName + "))";

But that gave me the same exception. Any idea what I am missing? I feel like your code is getting me very close to what I need.

sOltan