[英]Login authentication asp.net with active directory
我有一个项目,我需要使用活动目录登录到在 asp.net 中制作的网站,我按照本教程....
来自 ASP .NET 的 Active Directory 身份验证
现在我想获取用户组,我尝试了 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
我找到了一个更好的解决方案,比我在互联网上找到的任何答案都容易。
首先,我创建一个类来验证用户是否在活动目录中的组中:
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
如果您的服务器在 Windows 域中,它应该连接到 Active Directory,因此通过使用 Windows 身份验证,您已经使用 AD 凭据登录(因为用户之前必须在域中,否则浏览器将要求提供 AD 凭据)
要获取用户组,您可以使用DirectorySearcher类,显然当您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.