VB.NET以递归方式(间接)查找用户的组成员资格

时间:2017-09-06 04:25:47

标签: vb.net active-directory ldap

我使用以下代码来获取特定用户直接

的成员
    Public Function IsInGroup(ByVal username As String, ByVal password As String) As Collection
    Dim Groups As New Collection
    Dim domain = "registry"
    Dim dirEntry As New DirectoryEntry("LDAP://" & domain, username, password, DirectoryServices.AuthenticationTypes.Secure)
    Dim dirSearcher As New DirectorySearcher(dirEntry)
    dirSearcher.Filter = "(SAMAccountName=" + username + ")"
    dirSearcher.PropertiesToLoad.Add("memberOf")
    Dim propCount As Integer
    Try
        Dim dirSearchResults As SearchResult = dirSearcher.FindOne()
        propCount = dirSearchResults.Properties("memberOf").Count
        Dim dn As String
        Dim equalsIndex As String
        Dim commaIndex As String
        For i As Integer = 0 To propCount - 1
            dn = dirSearchResults.Properties("memberOf")(i)
            equalsIndex = dn.IndexOf("=", 1)
            commaIndex = dn.IndexOf(",", 1)
            If equalsIndex = -1 Then
                Return Nothing
            End If
            If Not Groups.Contains(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)) Then
                Groups.Add(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
            End If
        Next
    Catch ex As Exception
        If ex.GetType Is GetType(System.NullReferenceException) Then
            MessageBox.Show("Selected user isn't a member of any groups at this time.", "No groups listed", MessageBoxButtons.OK, MessageBoxIcon.Error)
            'they are still a good user just does not
            'have a "memberOf" attribute so it errors out.
            'code to do something else here if you want
        Else
            MessageBox.Show(ex.Message.ToString, "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Try
    'Console.WriteLine(Groups)
    Return Groups

End Function

但是如何获得用户是InDirectly成员的组?

想法?

1 个答案:

答案 0 :(得分:0)

您应该让Active Directory通过查询tokenGroups属性来为您执行此操作,而不是自己查询和枚举递归组成员资格。

tokenGroups属性是由Active Directory计算的SID数组,用于验证用户访问权限。

我们需要将这些SID转换为他们的sAMAccountNames以获取实际的组名。

在非托管代码中,可以通过调用DsCrackNames API或IADsNameTranslate接口来完成此操作。

在(VB).NET中,最简单的方法是使用公开GetAuthorizationGroups方法的UserPrincipal类(需要.NET Framework 3.5或更高版本)。

有关示例,请参阅https://www.remkoweijnen.nl/blog/2011/01/18/recursive-group-membership-in-powershell/。它在PowerShell中很容易翻译成VB.NET。