混合身份验证模式ASP.NET - 表单票证不会粘贴

时间:2015-11-18 19:00:53

标签: asp.net vb.net authentication mixed-mode

我在asp.net应用程序中遇到混合身份验证问题。我的应用程序使用集成身份验证为单一位置表单设置表单身份验证。集成的身份验证部分似乎按预期工作。我能够识别用户,提取角色并创建FormsAuthentication票证,但是当我重定向到default.aspx时,不会重新验证身份验证。它只是让我回到集成身份验证页面。

LOGIN.aspx(用于表单身份验证)

<asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser" TitleText=""></asp:Login>

Login.aspx.vb(表单身份验证后面的代码)

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security
Partial Class Login_Login
   Inherits System.Web.UI.Page
   Protected Sub ValidateUser(sender As Object, e As EventArgs)
      Dim intUserID As Integer = 0
      Dim strRoles As String = String.Empty
      Dim AdminConn As String = ConfigurationManager.ConnectionStrings("AdminConnectionString").ConnectionString
      Using conn As New SqlConnection(AdminConn)
         Using cmd As New SqlCommand("Validate_User")
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@Username", Login1.UserName)
            cmd.Parameters.AddWithValue("@Password", Login1.Password)
            cmd.Connection = conn
            conn.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            Do While reader.Read()
               intUserID = Convert.ToInt32(reader("UserId"))
               strRoles += reader(1).ToString() & ","
            Loop
            conn.Close()
         End Using
         Select Case intUserID
            Case -1
               Login1.FailureText = "Username and/or password is incorrect."
            Case -2
               Login1.FailureText = "Account is not enabled."
            Case Else
               Dim ticket As New FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, strRoles, FormsAuthentication.FormsCookiePath)
               Dim hash As String = FormsAuthentication.Encrypt(ticket)
               Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
               If ticket.IsPersistent Then
                  cookie.Expires = ticket.Expiration
               End If
               Response.Cookies.Add(cookie)
               Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet))
         End Select
      End Using
   End Sub

   Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
      Dim UserName As String = Session("AuthUser")
      Dim UserRoles As String = Session("UserRoles")
      If Not Me.IsPostBack Then
         If Me.Page.User.Identity.IsAuthenticated Then
            FormsAuthentication.SignOut()
            Response.Redirect("~/Login.aspx")
         End If
      End If
   End Sub
End Class

Global.asax(用于表单身份验证)

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
   If HttpContext.Current.User IsNot Nothing Then
      If HttpContext.Current.User.Identity.IsAuthenticated Then
         If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
            Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
            Dim ticket As FormsAuthenticationTicket = id.Ticket
            Dim userData As String = ticket.UserData
            Dim roles As String() = userData.Split(","c)
            HttpContext.Current.User = New GenericPrincipal(id, roles)
         End If
      End If
    End If
End Sub

WINLOGIN.aspx.vb(Windows身份验证背后的代码)

Imports System
Imports System.Web
Imports System.Web.Security
Partial Class WinLogin
   Inherits System.Web.UI.Page
   Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
      Dim redirectUrl As String = "~/Default.aspx
      Dim username As String = Request.ServerVariables("LOGON_USER")
      Dim roles1() As String = Roles.GetRolesForUser(username)
      If (Login(username, String.Join(",", roles1))) Then
         Response.Redirect(redirectUrl)
      End If
      If (Page.IsPostBack) Then
         If (Response.StatusCode = 401) Then
            Response.Redirect("~/Login.aspx")
         End If
      End If
   End Sub

    Private Function Login(strUser As String, strRole As String) As Boolean
      If (strRole > "") Then
         Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, strUser, DateTime.Now, DateTime.Now.AddYears(1), False, strRole)
         Dim strEncryptedTicket As String = FormsAuthentication.Encrypt(ticket)
         Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket)
         Context.Response.Cookies.Add(cookie)
         Return True
      End If
      Return False
    End Function
End Class

的Web.Config

<configuration>
   <system.web>
      <httpRuntime executionTimeout="240" maxRequestLength="20480" />
      <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
      <customErrors mode="Off" />
      <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
      <authentication mode="Forms">
         <forms cookieless="UseDeviceProfile" defaultUrl="~/Default.aspx" enableCrossAppRedirects="true" loginUrl="~/WinLogin.aspx" name=".ASPXAUTH" path="/" protection="All" requireSSL="false" slidingExpiration="true" timeout="10080"/>
      </authentication>
      <authorization>
         <deny users="?" />
      </authorization>
   </system.web>
   <location path="Login.aspx">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
      <system.webServer>
         <security>
            <authentication>
               <anonymousAuthentication enabled="true"/>
               <windowsAuthentication enabled="false"/>
            </authentication>
         </security>
      </system.webServer>
   </location>
   <location path="WinLogin.aspx">
      <system.web>
         <authorization>
            <deny users="?"/>
            <allow users="*"/>
         </authorization>
      </system.web>
      <system.webServer>
         <security>
            <authentication>
               <anonymousAuthentication enabled="false"/>
               <windowsAuthentication enabled="true"/>
            </authentication>
         </security>
      </system.webServer>
   </location>
   <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
      <validation validateIntegratedModeConfiguration="false" />
   </system.webServer>
</configuration>

0 个答案:

没有答案