Question

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.

Était-ce utile?

La 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.

Autres conseils

Anon's answer works for what I asked, but I also wanted to be able to search for other user's groups. The best way I've found to do this is to run the asp.net program's app pool under a service account, and then use my original code.

To do this in IIS Manager 7.5, go to the Application Pools, right click on the one your app is running under -> Advanced Settings, and change the identity from "ApplicationPoolIdentity" to a custom domain account.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top