Tulpep / Active-Directory-Object-Picker

The standard Active Directory object picker dialog for .NET

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get user's SID?

win32nipuh opened this issue · comments

I am testing the example code. But I do not see how to retrieve the SID of the selected user?

Sorry, no problem, it works fine.

For those who want to know how to solve this:

using(var dialog = new DirectoryObjectPickerDialog())
{
    dialog.AllowedObjectTypes = ObjectTypes.Users;
    dialog.MultiSelect = false;        
    dialog.AttributesToFetch.Add("objectSid");
    //LDAP has dozens of attributes, but almost all return null. In my experience objectSid is the only useful one.

    if (dialog.ShowDialog() == DialogResult.OK)
    {
        //FetchedAttributes contains attribute values from AttributesToFetch, in that order
        byte[] sidBytes = (byte[])dialog.SelectedObject.FetchedAttributes[0];
        
        //Now we can translate the SID to NT account (DOMAIN\user)
        var sid = new System.Security.Principal.SecurityIdentifier(sidBytes,0);
        System.Security.Principal.NTAccount user = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount));

        return user.Value;
    }
}