gpt4 book ai didi

c# - 使用 Windows 身份验证创建 PrincipalContext

转载 作者:行者123 更新时间:2023-12-03 19:16:08 26 4
gpt4 key购买 nike

我正在创建一个 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 数据库?我试过使用模拟,但它在 FindByIdentity 行上引发了 An operations error occurred 错误。如果我完全忘记了身份验证,我将限制返回的组数。

最佳答案

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

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 的结果,这就是我在这里所做的。

关于c# - 使用 Windows 身份验证创建 PrincipalContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com