首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何验证用户是否属于C#.NET中的Active Directory用户组

要验证用户是否属于C#.NET中的Active Directory用户组,您可以使用System.DirectoryServices.AccountManagement命名空间中的PrincipalContext和UserPrincipal类。以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.DirectoryServices.AccountManagement;

public class ActiveDirectoryHelper
{
    public static bool IsUserInGroup(string username, string groupName)
    {
        // 使用默认的Active Directory容器
        using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
        {
            // 创建一个UserPrincipal对象,用于查找用户
            UserPrincipal user = UserPrincipal.FindByIdentity(context, username);

            // 如果找到了用户,则检查其是否属于指定的组
            if (user != null)
            {
                // 创建一个GroupPrincipal对象,用于查找组
                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);

                // 如果找到了组,则检查用户是否属于该组
                if (group != null)
                {
                    return group.GetMembers(true).Contains(user);
                }
                else
                {
                    throw new ArgumentException("找不到指定的组", nameof(groupName));
                }
            }
            else
            {
                throw new ArgumentException("找不到指定的用户", nameof(username));
            }
        }
    }
}

在上面的代码中,我们首先使用PrincipalContext对象连接到Active Directory容器。然后,我们使用UserPrincipal.FindByIdentity方法查找用户。如果找到了用户,我们使用GroupPrincipal.FindByIdentity方法查找组。最后,我们使用GroupPrincipal.GetMembers方法检查用户是否属于该组。

请注意,此代码示例仅适用于本地Active Directory,而不适用于云计算中的Active Directory。如果您需要在云计算中使用Active Directory,您需要使用其他API和库。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券