简体   繁体   English

查找用户是否是 Active Directory 组 ASP.NET VB 的成员?

[英]Find If User is Member of Active Directory Group ASP.NET VB?

I am using Active Directory to authenticate users for an intranet site.我正在使用 Active Directory 对 Intranet 站点的用户进行身份验证。 I would like to refine the users that are authenticated based on the group they are in in Active Directory.我想根据他们在 Active Directory 中所在的组来优化经过身份验证的用户。 Can someone show me or point me to directions on how to find what groups a user is in in ASP.NET 4.0 (VB)?有人可以向我展示或指出有关如何在 ASP.NET 4.0 (VB) 中查找用户所在组的说明吗?

I realize this post is quite old but I thought I might update it with processes I am using.我意识到这篇文章已经很旧了,但我想我可能会用我正在使用的进程更新它。 (ASP.Net 4.0, VB) (ASP.Net 4.0, VB)

If using integrated windows security, on a domain.如果使用集成的 Windows 安全性,则在域上。

Page.User.IsInRole("domain\\GroupName") will check to see if the authenticated user is a member of the specified group. Page.User.IsInRole("domain\\GroupName")将检查通过身份验证的用户是否是指定组的成员。

If you would like to check another users group membership other than the authenticated user.如果您想检查经过身份验证的用户以外的其他用户组成员身份。

Two stage for checking multiple groups with the same user principal:检查具有相同用户主体的多个组的两个阶段:

Dim MyPrincipal As New System.Security.Principal.WindowsPrincipal _
     (New System.Security.Principal.WindowsIdentity("UserID"))
Dim blnValid1 As Boolean = MyPrincipal.IsInRole("domain\GroupName")

Single stage for checkin a single group:单阶段签入单个组:

Dim blnValid2 As Boolean = New System.Security.Principal.WindowsPrincipal _
     (New System.Security.Principal.WindowsIdentity("userID")).IsInRole("domain\GroupName")

NOTE:: The IsInRole method does work with nested groups.注意:: IsInRole 方法确实适用于嵌套组。 If you have a top level group with a sub group that is a member, and the user is a member of the sub group.如果您有一个顶级组和一个作为成员的子组,并且用户是该子组的成员。

I think I have the ultimate function to get all AD groups of an user included nested groups without explicit recursion:我想我有最终的功能来让一个用户的所有 AD 组包含嵌套组,而无需显式递归:

Imports System.Security.Principal导入 System.Security.Principal

Private Function GetGroups(userName As String) As List(Of String)
    Dim result As New List(Of String)
    Dim wi As WindowsIdentity = New WindowsIdentity(userName)

    For Each group As IdentityReference In wi.Groups
        Try
            result.Add(group.Translate(GetType(NTAccount)).ToString())
        Catch ex As Exception
        End Try
    Next

    result.Sort()
    Return result
End Function

So just use GetGroups("userID").所以只需使用 GetGroups("userID")。 Because this approach uses the SID of the user, no explicit LDAP call is done.由于此方法使用用户的 SID,因此不会执行显式 LDAP 调用。 If you use your own user name it will use the cached credentials and so this function is very fast.如果您使用自己的用户名,它将使用缓存的凭据,因此此功能非常快。

The Try Catch is necessary because in large companyies the AD is so big that some SIDs are getting lost in space. Try Catch 是必要的,因为在大型公司中,AD 非常大,以至于一些 SID 会丢失在空间中。

For those who may be interested, this is how I ended up coding it:对于那些可能感兴趣的人,这就是我最终编码的方式:

Dim ID As FormsIdentity = DirectCast(User.Identity, FormsIdentity)
    Dim ticket As FormsAuthenticationTicket = ID.Ticket
    Dim adTicketID As String = ticket.Name
    Dim adSearch As New DirectorySearcher
    adSearch.Filter = ("(userPrincipalName=" & adTicketID & ")")
    Dim adResults = adSearch.FindOne.Path
    Dim adResultsDirectory As New DirectoryEntry(adResults)
    Dim found As Boolean = False
    For Each entry In adResultsDirectory.Properties("memberOf")
        Response.Write(entry)
        Response.Write("<br/>")
        If entry = "CN=GroupName,CN=UserGroup,DC=my,DC=domain,DC=com" Then
            found = True
        End If

    Next
    If Not (found) Then
        Response.Redirect("login.aspx")
    End If

I found this here .我在这里找到了这个。

''' <summary>
''' Function to return all the groups the user is a member od
''' </summary>
''' <param name="_path">Path to bind to the AD</param>
''' <param name="username">Username of the user</param>
''' <param name="password">password of the user</param>
Private Function GetGroups(ByVal _path As String, ByVal username As String, _
                 ByVal password As String) As Collection
    Dim Groups As New Collection
    Dim dirEntry As New _
        System.DirectoryServices.DirectoryEntry(_path, username, password)
    Dim dirSearcher As New DirectorySearcher(dirEntry)
    dirSearcher.Filter = String.Format("(sAMAccountName={0}))", 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
    Return Groups
End Function
End Class

To just check if a user is member of a group including sub-groups just use:要检查用户是否是包括子组在内的组的成员,请使用:

    Public Function IsInGroup(ByVal objectName As String, groupName As String) As Boolean
        Try
            return New WindowsPrincipal(New WindowsIdentity(objectName)).IsInRole(groupName))
        Catch ex As Exception
        End Try

        Return False
    End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM