2017-09-06 79 views
0

我使用下面的代碼來獲取組特定用戶的直接VB.NET查找用戶組成員遞歸(間接)

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的成員?

想法?

回答

0

而不是查詢和枚舉遞歸組成員資格,你應該有Active Directory通過查詢tokenGroups屬性來爲你做這件事。

tokenGroups屬性是由Active Directory計算並用於驗證用戶訪問的SID的數組。

我們需要將這些SID轉換爲它們的sAMAccountNames以獲取實際的組名稱。

在非託管代碼中,可以通過調用DsCrackNames API或IADsNameTranslate接口來完成。 (VB).NET最簡單的方法是使用UserPrincipal類(需要.NET Framework 3.5或更高版本),它公開GetAuthorizationGroups方法。

查看https://www.remkoweijnen.nl/blog/2011/01/18/recursive-group-membership-in-powershell/舉例。它在PowerShell中,但轉換爲VB.NET很簡單。

+0

謝謝你 - 我會看看,如果tokenGroups更快,更好,那麼聽起來不錯:) –