I am trying to retrieve the user DirectoryEntry by SID which is the unique key to the Active Directory entry. Here is my code:
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (!(providerUserKey is SecurityIdentifier))
throw new ArgumentException("Invalid
ProviderUserKey");
SecurityIdentifier SID = providerUserKey as SecurityIdentifier;
int SIDLen = SID.BinaryLength;
byte[] SIDBuffer = new byte[SIDLen];
SID.GetBinaryForm(SIDBuffe
r, 0);
string filter = string.Format("(sAMAccount
Name=*)(ob
jectSid={0
})",
ConvertByteToStringSid(SID
Buffer));
string[] attribs={"sAMAccountName",
"objectSid", "mail", "name", "comment", "whenCreated", "pwdLastSet"};
using (DirectoryEntry root = this.GetRootDirectoryEntry
(""))
{
using (DirectorySearcher search = new DirectorySearcher(root))
{
try
{
search.Filter = filter;
foreach (string prop in attribs)
{
search.PropertiesToLoad.Ad
d(prop);
}
SearchResult resultItem = search.FindOne(); //Read the path
MembershipUser user = LoadUser(resultItem);
return user;
}
catch (Exception ex)
{
this.lastError="Not Found:" + SID.ToString() + ":" + ex.Message;
System.Diagnostics.Debug.W
riteLine(t
his.lastEr
ror);
return null;
}
}
}
}
/// <summary>
/// Converts the byte to string sid.
/// </summary>
/// <param name="sidBytes">The sid bytes.</param>
/// <returns></returns>
private string ConvertByteToStringSid(Byt
e[] sidBytes)
{
StringBuilder strSid = new StringBuilder();
strSid.Append("S-");
try
{
// Add SID revision.
strSid.Append(sidBytes[0].
ToString()
);
// Next six bytes are SID authority value.
if (sidBytes[6] != 0 || sidBytes[5] != 0)
{
string strAuth = String.Format
("0x{0:2x}{1:2x}{2:2x}{3:2
x}{4:2x}{5
:2x}",
(Int16)sidBytes[1],
(Int16)sidBytes[2],
(Int16)sidBytes[3],
(Int16)sidBytes[4],
(Int16)sidBytes[5],
(Int16)sidBytes[6]);
strSid.Append("-");
strSid.Append(strAuth);
}
else
{
Int64 iVal = (Int32)(sidBytes[1]) +
(Int32)(sidBytes[2] << 8) +
(Int32)(sidBytes[3] << 16) +
(Int32)(sidBytes[4] << 24);
strSid.Append("-");
strSid.Append(iVal.ToStrin
g());
}
// Get sub authority count...
int iSubCount = Convert.ToInt32(sidBytes[7
]);
int idxAuth = 0;
for (int i = 0; i < iSubCount; i++)
{
idxAuth = 8 + i * 4;
UInt32 iSubAuth = BitConverter.ToUInt32(sidB
ytes, idxAuth);
strSid.Append("-");
strSid.Append(iSubAuth.ToS
tring());
}
}
catch (Exception ex)
{
lastError = "Error building SID str:"+ex.Message;
System.Diagnostics.Debug.W
riteLine(l
astError);
return "";
}
return strSid.ToString();
}
It tries to do a directory search with a filter of:
"(sAMAccountName=*)(object
Sid=S-1-5-
21-1993962
763-492894
223-682003
330-1126)"
but fails on the 'SearchResult resultItem = search.FindOne()' line with an exception of "Unknown error (0x80005000)"