迅速确定一个用户帐户是否是AD组的成员最好的方法

迅速确定一个用户帐户是否是AD组的成员最好的方法

本文介绍了迅速确定一个用户帐户是否是AD组的成员最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一些code,拉下来的用户在一组,然后遍历列表,通过该组,以确定是否一个给定的帐户存在,但似乎应该有一个更简洁(也许更快)的方式来做到这一点。

I currently have some code that pulls down a list of users in a group and then iterates through that group to determine if a given account exists, but it seems like there ought to be a more concise (and perhaps faster) way to accomplish this.

这code(VB.NET)尝试使用组对象的成员属性,但它返回假的,即使用户是该组的成员。任何人都可以看到我在做什么错在这里?

This code (VB.NET) attempts to use the member property of the group object, but it is returning false even when the user is a member of that group. Can anyone see what I am doing wrong here?

Dim group As DirectoryEntry =  GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)
Dim user As DirectoryEntry =GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)

Return group.Properties("member").Contains(user.Path)

FYI:本GetNetworkObject调用只返回一个DirectoryEntry对象,我已经证实了正确的对象被返回为组和用户对象

FYI: The GetNetworkObject calls just return a directoryEntry object, I have confirmed that the correct object is being returned for both the group and user object.

推荐答案

如果您使用的是.NET 3.5栈,System.DirectoryServices.AccountManagement.dll装配对AD的顶部一个不错的API。下面的方法可以实现,以解决您的问题:

If you are on .NET 3.5 stack, System.DirectoryServices.AccountManagement.dll assembly has a nice API on top of AD. The following method can be implemented to solve your issue:

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);
    }
}

// Usage:
bool result = IsUserMemberOf("CONTOSO\\john.doe", "CONTOSO\\Administrators");

我不知道这个方法执行,但它是一个干净的解决方案。

I don't know how this method performs but it is a clean solution.

这篇关于迅速确定一个用户帐户是否是AD组的成员最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 06:02