使用Windows身份验证创建PrincipalContext

时间:2013-01-18 21:00:21

标签: c# asp.net active-directory windows-authentication directoryservices

我正在创建一个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
}

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

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

2 个答案:

答案 0 :(得分: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         
    }          
} 

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

答案 1 :(得分:0)

Anon的回答适用于我的要求,但我也希望能够搜索其他用户的群组。我发现这样做的最好方法是在服务帐户下运行asp.net程序的应用程序池,然后使用我的原始代码。

要在IIS管理器7.5中执行此操作,请转到应用程序池,右键单击运行应用程序的应用程序池 - &gt;高级设置,并将身份从“ApplicationPoolIdentity”更改为自定义域帐户。