【问题标题】:Retrieve user information and check if member of a group in active directory using VB.NET使用 VB.NET 检索用户信息并检查活动目录中的组成员是否
【发布时间】:2010-09-07 20:08:10
【问题描述】:

我正在使用以下有效的代码将用户登录到针对活动目录在 VB.NET 中构建的应用程序。

这段代码很好用,但我需要检索用户的名字、姓氏、显示名称,并检查用户是否属于某个组。

我尝试了多种形式的 adResults.Property("displayname").ToString() 等,但无法正常工作。

有人知道如何做我想做的事吗?

这是我现在正在使用的代码,提前致谢。

Public Function ValidateActiveDirectoryLogin(ByVal sDomain As String, ByVal sUserName As String, ByVal sPassword As String) As Boolean

    Dim bSuccess As Boolean = False
    Dim adEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" & sDomain, sUserName, sPassword)
    Dim adSearcher As New System.DirectoryServices.DirectorySearcher(adEntry)
    adSearcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    Try
        Dim adResults As System.DirectoryServices.SearchResult = adSearcher.FindOne
        bSuccess = Not (adResults Is Nothing)
    Catch ex As Exception
        bSuccess = False
        MsgBox("Error")
    End Try

    Return bSuccess

End Function 

【问题讨论】:

    标签: .net vb.net active-directory


    【解决方案1】:

    查看 System.DirectoryServices.AccountManagemment 命名空间。 userprincipal 对象拥有您需要的一切以及更多。 Here's an explanation 了解如何使用此 API。

    编辑:实际上使用起来要简单得多。看看这个示例代码:

    Dim userName = Environment.UserName
    
    ' create a domain context
    Dim DC = New PrincipalContext(ContextType.Domain)
    
    ' find a user in the domain
    Dim user = UserPrincipal.FindByIdentity(DC, userName)
    
    ' get the user's groups
    Dim groups = user.GetGroups()
    
    ' get the user's first and last name
    Dim firstName = user.GivenName
    Dim lastName = user.SurName
    
    ' get the distinguishednames for all groups of the user
    Dim groupNames = From g in groups Select g.DistinguishedName
    ' etc...
    

    【讨论】:

    • 确实这比我想要的要多,但如果这是获得我需要的东西的唯一方法,我肯定会看看它,但无论如何可以从系统中检索用户信息.DirectoryServices.SearchResult 对象?让它尽可能简单会很好。谢谢=)
    • @Tom 实际上使用起来要简单得多,看看我的编辑
    【解决方案2】:

    ..并快速将组名的内容(来自 Jeroenh 的出色答案)转储到列表框中:

        ListBox1.DataSource = groupnames.ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多