Venyla
Venyla

Reputation: 87

How can I lookup an IdentityReference in Active Directory?

I'm trying to read out users, which are having permisson to read a document. I could already connect to the directory and read out the Identity Reference, but now I want to look the ID up in the Active Directory and read out the name from this ID.

DirectorySecurity ds = Directory.GetAccessControl(path);
                     AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                     foreach (FileSystemAccessRule fsar in arc)
                     {
                             StringBuilder sb = new StringBuilder();
                             sb.AppendLine("Identity : " + fsar.IdentityReference.Value);


                             sb.AppendLine("FileSystemRights : " + fsar.FileSystemRights);
                             + fsar.PropagationFlags);


                             Console.WriteLine(sb.ToString());

And I could already connect with the AD-Server, now I want to search with the DirectorySearcher for the IdentityReference.

 System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(@"LDAP://mydomain.local/");
                              entry.Username = username;
                              entry.Password = password;

                             System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);

mySearcher.Filter = "(......)"; //searching for IdentityReference

How can I do that?

btw: I'm a C# beginner an thankfull for every answer.

Upvotes: 3

Views: 3451

Answers (1)

fejesjoco
fejesjoco

Reputation: 11903

As you can see here, an identity reference is either a SID (S-1-2-3434-1234243...) or an NT account name (DOMAIN\john.doe). These can be translated into each other with the Translate method, so you can use either one. Decide which one you like and do the translation. It doesn't matter if the reference is already in that format, it's easier to do the translation always and you can be sure it will be whatever you like.

For finding users based on either of those attributes, I would suggest using the PrincipalContext.FindByIdentity method. It supports both SID and login name lookup, among others, and it is a lot easier than an LDAP filter.

But of course, you can write an LDAP filter if you like. I'm not sure about the login name, because it is not directly stored in AD in that format, but you can definitely search for a SID if you write a query for the objectSid attribute, like (objectSid=S-1-2-3434...).

Upvotes: 2

Related Questions