登录认证asp.net与活动目录

时间:2012-11-16 19:19:47

标签: asp.net vb.net authentication active-directory

我有一个项目,我需要使用活动目录登录到asp.net制作的网站,我按照本教程....

Active Directory Authentication from ASP .NET

现在我想获取用户的组,我尝试了default.aspx.vb页面中的下一个代码,但是不起作用..

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Response.Write("Hello, " + Server.HtmlEncode(User.Identity.Name))

    Dim id As FormsIdentity = CType(User.Identity, FormsIdentity)

    If id IsNot Nothing Then

        Dim ticket As FormsAuthenticationTicket = id.Ticket
        Response.Write("<p/>TicketName: " + ticket.Name)
        Response.Write("<br/>Cookie Path: " + ticket.CookiePath)
        Response.Write("<br/>Ticket Expiration: " + ticket.Expiration.ToString())
        Response.Write("<br/>Expired: " + ticket.Expired.ToString())
        Response.Write("<br/>Persistent: " + ticket.IsPersistent.ToString())
        Response.Write("<br/>IssueDate: " + ticket.IssueDate.ToString())
        Response.Write("<br/>UserData: " + ticket.UserData)
        Response.Write("<br/>Version: " + ticket.Version.ToString())
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

我找到了更好的解决方案,比我在互联网上找到的任何答案都更容易。

首先,我创建一个类来验证用户是否在活动目录中的组中:

Imports System.Security.Principal   

Public Class AutorizationFun
    Dim access As Boolean = False
    Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
    Public User As WindowsPrincipal = New WindowsPrincipal(id)

地区“群组验证”

'Belongs to sample group
Private Function inSampleGroup() As Boolean
    Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP")
End Function
Private Function inSampleGroup2() As Boolean
    Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP2")
End Function

结束地区

Public Function ProgramsAccsess(ByVal vPage As String) As Boolean
    access = False

    Select Case vPage
        Case "~/Sample.aspx"
            If inSampleGroup() Then
                access = True
            End If
        '---------------------------------------------------------------------
    End Select
    '*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
    'access = True
    '*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
    Return access
End Function   

End Class

然后你必须在所有页面后面的代码中创建一个函数:

'create var
    Dim ValidateUser As New AutorizationFun

    Protected Sub VerifyAccessPage()
        If ValidateUser.ProgramsAccsess(Request.AppRelativeCurrentExecutionFilePath) = False Then
            Response.Redirect("~/DeniedAccess.aspx")
        End If
    End Sub

要完成必须在Page_load事件中使用该函数:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'check whether page is postback or not            
        If Not Page.IsPostBack Then
            VerifyAccessPage()
        End If
    End Sub

答案 1 :(得分:0)

如果您的服务器位于Windows域中,则应将其连接到Active Directory,因此通过使用Windows身份验证,您已使用AD凭据登录(因为用户之前必须在域中,否则将要求其提供AD凭据通过浏览器)

要获取用户组,您可以使用DirectorySearcher课程,显然是