How to determine user DN after authentication agai

2019-08-10 14:28发布

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

Update:

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?

2条回答
The star\"
2楼-- · 2019-08-10 14:41

When I add a new user manually in the active directory, the 'distinguished Name' cannot be define manually but the convention seems to be the first name + ' ' + the last name. In this case, why not trying to get the 'distinguished name' following this pattern. I also found that if I just specified a first name to create a non-human user, the 'distinguihed name' is the equal to the first name without space after.

I follow this pattern in my application and it works and it's much simple than trying to create custom query to search user.

查看更多
Melony?
3楼-- · 2019-08-10 14:44

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)
   searchResult = src[0];
  }

  if (searchResult != null)
  {
    // Get DN here
    string DN = searchResult.Properties["distinguishedName"][0].ToString();
  }
查看更多
登录 后发表回答