使用Windows身份验证创建PrincipalContext

Cav*_*len 2 c# asp.net directoryservices active-directory windows-authentication

我正在创建一个PrincipalContext对象,用于从我们的AD数据库中检索用户的组(我们使用它们对站点的各个部分进行身份验证).

以前这是使用表单身份验证完成的,因此代码看起来像这样

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
}
Run Code Online (Sandbox Code Playgroud)

但是,我们最近切换到Windows身份验证,我无法再访问用户的密码.

如何使用当前用户的凭据搜索AD数据库?我尝试过使用模拟,但它会在行An operations error occurred上抛出错误FindByIdentity.如果我忘记了身份验证,那么我在返回的组数量上受到限制.

Bot*_*ous 6

这是我使用的方法,您可以将其更改为返回集合:

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         
    }          
} 
Run Code Online (Sandbox Code Playgroud)

我假设你想要结果IEnumerable,这就是我在这里所做的.