Cookie 与 FormsAuthentication.SetAuthCookie() 方法混淆 [英] Cookie Confusion with FormsAuthentication.SetAuthCookie() Method

查看:30
本文介绍了Cookie 与 FormsAuthentication.SetAuthCookie() 方法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在 StackOverflow 上有很多关于这个的帖子,但我仍然无法解决我的确切问题.要点如下:

So there are lots of posts on StackOverflow regarding this, but I still was unable to solve my exact problem. Here's the gist:

我有一个需要身份验证的网站.我使用标准的 .NET FormsAuthentication.SetAuthCookie() 方法来持久化用户的会话.

I have a website that requires authentication. I am using the standard .NET FormsAuthentication.SetAuthCookie() method to persist the user's session.

我的问题是:在 web.config 文件中,/system.web/authentication/forms"节点有一个超时属性.如果我将此值设置为 30 分钟,这是用户在会话到期之前可以保持的用户不活动时间吗?

My question is this: In the web.config file, there is a timeout attribute to the "/system.web/authentication/forms" node. If I set this value to say, 30 minutes, is this the time of user inactivity the user can have before their session expires?

我问的原因是,无论我将此值设置为什么,如果我在 SetAuthCookie() 中将持久性设置为 true,则 cookie 集的到期时间为 90 分钟.如果我在 SetAuthCookie() 中将持久性设置为 false,则 cookie 过期时间设置为会话结束".

The reason I ask is that no matter what I set this value to, if I set persistence to true in SetAuthCookie(), the expiration on the cookie set is 90 minutes. If I set persistence to false in SetAuthCookie(), the cookie expiration is set to "end of session".

实际设置的超时"属性值是什么,如何获得持续一个月或一年或更长时间的持久性 cookie?

What is that "Timeout" attribute value actually setting, and how can I get a persistent cookie that lasts a month or a year or longer?

推荐答案

你在 /system.web/authentication/forms 中找到的参数 timeout 是持续时间的超时(以分钟为单位)身份验证票.

The parameter timeout you've found in /system.web/authentication/forms is the timeout (in minutes) of the duration of authentication ticket.

这意味着在一段时间不活动后,系统会提示用户再次登录.如果您尝试检查此 My.Profile.Current.IsAuthenticated,它将是 false.

This means that after a certain amount of time of inactivity, a user is prompted to login again. If you try to check this My.Profile.Current.IsAuthenticated it will be false.

您可以选择不保留 cookie.在这种情况下,如果您的票过期,您的 cookie 也会过期.cookie(如果被持久化)的目的是在用户返回您的网站时记住他/她.

You can choose not to persist the cookie. In this situation if your ticket expires, your cookie expires too. The cookie (in case is persisted) has a purpose to remember the user if he/she comes back to your site.

您可能希望将 cookie 保留 10 年,这样用户就不必再次插入用户名和密码,除非他们选择删除 cookie.即使浏览器关闭(持久化时),cookie 也是有效的.

You might want to persist your cookie for 10 years so the user will never have to insert username and password again, unless they've chosen to delete the cookie. The cookie is valid even if the browser is closed (when it is persisted).

另一个要记住的重要事情是参数slidingExpiration:

Another important thing to remember is the parameter slidingExpiration:

<authentication mode="Forms">
    <forms loginUrl="~/Partner/LogOn" defaultUrl="~/Home/Index" 
           timeout="30" slidingExpiration="true" />
</authentication>

如果这是真的,您的身份验证票将在您网站上的每次活动时更新:刷新页面等.

if it's true your authentication ticket will be renewed every time there's activity on your site: refresh of the page etc.

你能做的——以及我所做的——就是像这样编写你自己的 cookie:

What you can do - and what I've done - is to write your own cookie like this:

 FormsAuthenticationTicket authTicket = new
     FormsAuthenticationTicket(1, //version
     userName, // user name
     DateTime.Now,             //creation
     DateTime.Now.AddMinutes(30), //Expiration (you can set it to 1 month
     true,  //Persistent
     userData); // additional informations

更新

我已经实现了这个例程,因为我想将我的组存储在一个加密的 cookie 中:

I've implemented this routine cause I want to store my groups in an encrypted cookie:

Dim authTicket As System.Web.Security.FormsAuthenticationTicket = _
        New System.Web.Security.FormsAuthenticationTicket( _
            1, _
            UserName, _
            Now, _
            Now.AddYears(100), _
            createPersistentCookie, _
            UserData)

Dim encryptedTicket As String = System.Web.Security.FormsAuthentication.Encrypt(authTicket)

Dim authCookie As HttpCookie = New HttpCookie( _
    System.Web.Security.FormsAuthentication.FormsCookieName, _
    encryptedTicket)

If (createPersistentCookie) Then
    authCookie.Expires = authTicket.Expiration
End If

Response.Cookies.Add(authCookie)

如您所见,我已将身份验证 cookie 和身份验证票证的过期时间设置为相同的超时时间(仅在持久化时).

As you can see I've set the expiration of the authentication cookie and the authentication ticket with the same timeout (only when persisted).

我尝试过的另一件事是将用户名和密码存储在加密的 cookie 中.每次加载主页时,我都会检查 My.Profile.Current.IsAuthenticated 以查看身份验证是否仍然有效.如果没有,我再次读取 cookie,获取用户名和密码,并在 DB 上检查:

Another thing that I've tried is to stored username and password in the encrypted cookie. Everytime a masterpage is loaded I check My.Profile.Current.IsAuthenticated to see if the authentication is still valid. If not I read the cookie again, get the username and password, and check it on the DB:

Public Function ReadCookieAuthentication(ByVal Context As System.Web.HttpContext) As Security.CookieAuth

    Dim CookieUserData = New Security.CookieAuth()

    Dim cookieName As String = System.Web.Security.FormsAuthentication.FormsCookieName
    Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)

    If (Not (authCookie Is Nothing)) Then
        Dim authTicket As System.Web.Security.FormsAuthenticationTicket = Nothing
        Try
            authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value)
            If (Not (authTicket Is Nothing)) Then
                If (authTicket.UserData IsNot Nothing) AndAlso Not String.IsNullOrEmpty(authTicket.UserData) Then
                    CookieUserData = New JavaScriptSerializer().Deserialize(Of Security.CookieAuth)(authTicket.UserData.ToString)
                End If
                CookieUserData.UserName = authTicket.Name
            End If
        Catch ex As Exception
            ' Do nothing.
        End Try
    End If

    Return (CookieUserData)

End Function

Security.CookieAuth 是我创建的一个对象,用于返回用户名和密码.
CookieUserData 是我存放密码和群组的存储空间(我以 json 格式保存).

Security.CookieAuth is an object I've created to return username and password.
CookieUserData is the storage (I save in json format) where I put my password and groups.

这篇关于Cookie 与 FormsAuthentication.SetAuthCookie() 方法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆