我正在使用下面的代码来检查给定的用户是否属于AD中的通讯组。
static bool IsUserMemberOf(string userName, string groupName)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
我正在调用上述方法,其值为IsUserMemberOf("domain\\username","domain\\groupname")
但是我看到一个空指针异常,因为groupPrincipal
具有空值。
这方面有帮助吗?
仅表示:
groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
返回空指针,因为您的域中不存在您的组。您只需要测试var ctx
,userPrincipal
和groupPrincipal
。
实际上,我的网上论坛与我要查询的用户不在同一个域中:我对程序进行了以下更改,现在可以工作。
而且我这样打电话:
IsUserMemberOf("domain1\\username","domain2\\groupname")
static bool IsUserMemberOf(string userName, string groupName)
{
using (var ctx = new PrincipalContext(ContextType.Domain,"domain1"))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain,"domain2"), groupName))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
//如何检查用户是否在AD成员和特定的AD组成员中
//This Reference and DLL must be attach in your project
//using System.DirectoryServices.AccountManagement;
public bool IsAuthenticated(string username, string pwd)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "xxx.com")) // Your Domain Name
{
if (pc.ValidateCredentials(username, password)) //User and Password is OK for Active Directory
{
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username); //Get User Active Directory Information Details
if (user != null)
{
var groups = user.GetAuthorizationGroups(); // Get User Authorized Active Directory Groups
foreach (GroupPrincipal group in groups)
{
if (group.Name.Equals("SpecificActiveDirectoryGroupName")) //Check if user specific group members
{
return true;
}
}
}
}
}
return false;
}