我正在尝试获取当前的 windows 用户并查看该用户是否属于 Active Directory 中的某个组。用户名信息找到“Harper\TSmith”,这看起来不错,但是当我到达
UserPrincipal uPrincipal = Psearch.FindOne() as UserPrincipal
行 UPrincipal 为空。想不通为什么。我在底部还有一个验证器类,它作为布尔方法来查看它们是否属于该特定组。
PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
UserPrincipal findUser = new UserPrincipal(principalCtx);
//findUser.Name = Environment.UserName;
findUser.Name = WindowsIdentity.GetCurrent().Name;
PrincipalSearcher pSearch = new PrincipalSearcher();
pSearch.QueryFilter = findUser;
UserPrincipal uPrincipal = pSearch.FindOne() as UserPrincipal;
Validator validate = new Validator();
//validate.IsUserInGroup("VisualOne", uPrincipal);
if (validate.IsUserInGroup("MyGroup", uPrincipal))
{
var MemberShipForm = new Membership();
MemberShipForm.Show();
}
public bool IsUserInGroup(string groupName, UserPrincipal user)
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, "Harper");
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "MyGroup");
if (user.IsMemberOf(group))
{
return true;
}
return false;
}