Search code examples
c#asp.netactive-directorywindows-authenticationdirectoryservices

Create PrincipalContext using windows authentication


I'm creating a PrincipalContext object for retrieving a user's groups from our AD database (we use these then for authentication to various parts of the site).

This used to be done using forms authentication, so the code looked something like this

PrincipalContext pc =
    new PrincipalContext(ContextType.Domain, "domain.com", username, password);

UserPrincipal usp =
    UserPrincipal.FindByIdentity(pc, IdentityType.Guid, user.Guid.ToString());

foreach (var group in usp.GetGroups())
{
    // Add group to collection
}

However, we recently switched to windows authentication, and I no longer have access to the user's password.

How can I search the AD database using the current user's credentials? I've tried using impersonation, but it throws an An operations error occurred error on the FindByIdentity line. If I forget about authentication all together I'm limited in the number of groups that are returned.


Solution

  • Here is a method I use, You could change it to return a collection:

    public static List<string> getGrps(string userName)          
    {          
        List<string> grps = new List<string>();          
    
        try          
        {
            var currentUser = UserPrincipal.Current;
            RevertToSelf();             
            PrincipalSearchResult<Principal> groups = currentUser.GetGroups();          
            IEnumerable<string> groupNames = groups.Select(x => x.SamAccountName);          
            foreach (var name in groupNames)          
            {          
                grps.Add(name.ToString());          
            }          
            return grps;          
        }          
        catch (Exception ex)          
        {          
            // Logging         
        }          
    } 
    

    I assume you want the results IEnumerable, which is what I did here.