asp登录会话

时间:2014-05-01 16:49:19

标签: asp.net session cookies session-cookies

大家好我有登录,当用户在系统中验证时,他可以通过页面浏览,但我的问题是当用户意外关闭浏览器并再次回到网站时,他需要验证登录时,我创建了以下cookie:

    Dim cookie As New HttpCookie("myCookie")
    cookie.Value = Usuario.Cve_Usuario 
    cookie.Expires = DateTime.Now.AddDays(2)
    Response.Cookies.Add(cookie)

    If Not User.Identity.IsAuthenticated OrElse Session("UserCookie") Is Nothing Then
       FormsAuthentication.SignOut()
       FormsAuthentication.RedirectToLoginPage()
       Response.End()
    End if

总结:当浏览器关闭并返回网站时,只有当天是在同一天,否则他会在系统中进行验证。

任何想法,一些教程都很受欢迎。

感谢您的评论。

1 个答案:

答案 0 :(得分:0)

在您的代码中,您创建Cookie然后检查它。应该有不同的场景:

  1. 如果没有cookie,您可以通过表单和设置cookie来验证用户
  2. 如果出现cookie,则使用cookies'值
  3. 实施例

    Private Sub cmdLogin_ServerClick(sender As Object, e As System.EventArgs)
    If ValidateUser(txtUserName.Value, txtUserPass.Value) Then
        Dim tkt As FormsAuthenticationTicket
        Dim cookiestr As String
        Dim ck As HttpCookie
        tkt = New FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data")
        cookiestr = FormsAuthentication.Encrypt(tkt)
        ck = New HttpCookie(FormsAuthentication.FormsCookieName, cookiestr)
        If chkPersistCookie.Checked Then
            ck.Expires = tkt.Expiration
        End If
        ck.Path = FormsAuthentication.FormsCookiePath
        Response.Cookies.Add(ck)
    
        Dim strRedirect As String
        strRedirect = Request("ReturnUrl")
        If strRedirect Is Nothing Then
            strRedirect = "default.aspx"
        End If
        Response.Redirect(strRedirect, True)
    Else
        Response.Redirect("logon.aspx", True)
    End If
    End Sub
    

    在global.asax

    Protected Sub FormsAuthentication_OnAuthenticate(sender As [Object], e As FormsAuthenticationEventArgs)
    If FormsAuthentication.CookiesSupported = True Then
        If Request.Cookies(FormsAuthentication.FormsCookieName) IsNot Nothing Then
            Try
                'let us take out the username now                
                Dim username As String = FormsAuthentication.Decrypt(Request.Cookies(FormsAuthentication.FormsCookieName).Value).Name
    
                'let us extract the roles from our own custom cookie
                Dim roles As String = DBHelper.GetUserRoles(username)
    
                'Let us set the Pricipal with our user specific details
                e.User = New System.Security.Principal.GenericPrincipal(New System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(";"C))
                    'somehting went wrong
            Catch generatedExceptionName As Exception
            End Try
        End If
    End If
    End Sub
    

    请参阅完整示例here