Solved

Get ActiveDirectory User by ObjectSID

Posted on 2006-07-06
3
8,015 Views
Last Modified: 2008-03-17
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(SIDBuffer, 0);
            string  filter = string.Format("(sAMAccountName=*)(objectSid={0})",
                ConvertByteToStringSid(SIDBuffer));

           
            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.Add(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.WriteLine(this.lastError);
                        return null;
                    }
                }
            }
        }
        /// <summary>
        /// Converts the byte to string sid.
        /// </summary>
        /// <param name="sidBytes">The sid bytes.</param>
        /// <returns></returns>
        private string ConvertByteToStringSid(Byte[] 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:2x}{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.ToString());
                }

                // 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(sidBytes, idxAuth);
                    strSid.Append("-");
                    strSid.Append(iSubAuth.ToString());
                }
            }
            catch (Exception ex)
            {
                lastError = "Error building SID str:"+ex.Message;
                System.Diagnostics.Debug.WriteLine(lastError);
                return "";
            }
            return strSid.ToString();
        }

It tries to do a directory search with a filter of:
  "(sAMAccountName=*)(objectSid=S-1-5-21-1993962763-492894223-682003330-1126)"
but fails on the 'SearchResult resultItem = search.FindOne()' line with an exception of "Unknown error (0x80005000)"
0
Comment
Question by:MogalManic
3 Comments
 
LVL 20

Accepted Solution

by:
ihenry earned 500 total points
ID: 17075687
If you look at the list of generic ADSI error codes in MSDN, the 0x80005000 hex decimal value is referred as E_ADS_BAD_PATHNAME. This means, the AD path you used to bind to AD could be invalid. Take a look closer to the path to see whether it is in the correct syntax and you didn't make any typo like putting a space or some other invalid character. Another possible cause would be security issue, which is the most tricky part when dealing with directory services. But if you can ensure that the user credential you used to run the code or to bind AD (if you explicitly pass user name and password to the DirectoryEntry object) has enough permissions to access and search user information, then all should be good.

Look at MSDN library, there should be enough information for you to solve this problem. If you get stumped again, please check back for more discussion.

http://msdn.microsoft.com/library/en-us/dsportal/dsportal/directory_services_portal.asp

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Interview questions for support of a legacy ASP.NET site 4 58
Turn on intranet settings 1 56
Visual Studio 2013 and Eclipse Neon 6 36
.NET 2008 VB and C# 6 27
IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question