代码之家  ›  专栏  ›  技术社区  ›  Chase Florell

如何在ASP.NET成员资格cookie中存储自定义数据

  •  4
  • Chase Florell  · 技术社区  · 14 年前

    有人能给我一个在ASP.NET成员资格cookie中存储自定义数据的示例(或给我指出正确的方向)吗?

    我需要向cookie中添加一些自定义属性,如userid和urlslug,并且能够以检索用户名的相同方式检索信息。

    编辑:

    我使用了代码诗人的例子,并提出了以下内容。

    当我在 Dim SerializedUser As String = SerializeUser(userData) 价值 userData 是正确的。它拥有我所期望的所有属性。

    我现在遇到的问题是当我 Dim userdata As String = authTicket.UserData (断点),值为 "" . 我很想知道我做错了什么。

    这是密码。

    Imports System
    Imports System.Web
    Imports System.Web.Security
    
    Namespace Utilities.Authentication
        Public NotInheritable Class CustomAuthentication
            Private Sub New()
            End Sub
    
            Public Shared Function CreateAuthCookie(ByVal userName As String, ByVal userData As Domain.Models.UserSessionModel, ByVal persistent As Boolean) As HttpCookie
    
                Dim issued As DateTime = DateTime.Now
                ''# formsAuth does not expose timeout!? have to hack around the
                ''# spoiled parts and keep moving..
                Dim fooCookie As HttpCookie = FormsAuthentication.GetAuthCookie("foo", True)
                Dim formsTimeout As Integer = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes)
    
                Dim expiration As DateTime = DateTime.Now.AddMinutes(formsTimeout)
                Dim cookiePath As String = FormsAuthentication.FormsCookiePath
    
                Dim SerializedUser As String = SerializeUser(userData)
    
                Dim ticket = New FormsAuthenticationTicket(0, userName, issued, expiration, True, SerializedUser, cookiePath)
                Return CreateAuthCookie(ticket, expiration, persistent)
            End Function
    
            Public Shared Function CreateAuthCookie(ByVal ticket As FormsAuthenticationTicket, ByVal expiration As DateTime, ByVal persistent As Boolean) As HttpCookie
                Dim creamyFilling As String = FormsAuthentication.Encrypt(ticket)
                Dim cookie = New HttpCookie(FormsAuthentication.FormsCookieName, creamyFilling) With { _
                 .Domain = FormsAuthentication.CookieDomain, _
                 .Path = FormsAuthentication.FormsCookiePath _
                }
                If persistent Then
                    cookie.Expires = expiration
                End If
    
                Return cookie
            End Function
    
    
            Public Shared Function RetrieveAuthUser() As Domain.Models.UserSessionModel
                Dim cookieName As String = FormsAuthentication.FormsCookieName
                Dim authCookie As HttpCookie = HttpContext.Current.Request.Cookies(cookieName)
                Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
                Dim userdata As String = authTicket.UserData
    
                Dim usersessionmodel As New Domain.Models.UserSessionModel
                usersessionmodel = DeserializeUser(userdata)
                Return usersessionmodel
            End Function
    
    
            Private Shared Function SerializeUser(ByVal usersessionmodel As Domain.Models.UserSessionModel) As String
                Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
                Dim mem As New IO.MemoryStream
                bf.Serialize(mem, usersessionmodel)
                Return Convert.ToBase64String(mem.ToArray())
            End Function
    
            Private Shared Function DeserializeUser(ByVal serializedusersessionmodel As String) As Domain.Models.UserSessionModel
                Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
                Dim mem As New IO.MemoryStream(Convert.FromBase64String(serializedusersessionmodel))
                Return DirectCast(bf.Deserialize(mem), Domain.Models.UserSessionModel)
            End Function
        End Class
    End Namespace
    

    这里是我创造所有魔法的地方。此方法位于继承的“baseController”类中 System.Web.Mvc.Controller

    Protected Overrides Function CreateActionInvoker() As System.Web.Mvc.IActionInvoker
    
                If User.Identity.IsAuthenticated Then ''# this if statement will eventually also check to make sure that the cookie actually exists.
    
                    Dim sessionuser As Domain.Models.UserSessionModel = New Domain.Models.UserSessionModel(OpenIdService.GetOpenId(HttpContext.User.Identity.Name).User)
                    HttpContext.Response.Cookies.Add(UrbanNow.Core.Utilities.Authentication.CustomAuthentication.CreateAuthCookie(HttpContext.User.Identity.Name, sessionuser, True))
                End If
    End Function
    

    下面是我如何尝试检索信息。

     Dim user As Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser
    
    2 回复  |  直到 10 年前
        1
  •  4
  •   Community CDub    7 年前

    根据具体情况,使用单独的cookie 可以 是一个可行的选择,但在我看来是次优的原因有几个,包括简单的事实,你必须管理多个cookie以及管理cookie的生命周期。

    将自定义信息合并到表单票据中最可靠的策略是利用 userData 票据字段。这正是它的作用所在。

    您可以轻松地将自定义数据存储在 用户数据 票据字段。

    关于要存储在票据中的数据的大小,需要注意一些问题 here

    here 是一个小类,可以帮助您在窗体通知单中存储自定义数据。

        2
  •  6
  •   this. __curious_geek    14 年前

    首先,ASP.NET成员资格提供程序不编写任何cookie,身份验证cookie是由FormsAuthentication编写的。

    其次,为什么要干涉认证cookie呢?你可以在一个单独的饼干里做这个。你可以这样做。

    将键值写入cookie。

    //create a cookie
    HttpCookie myCookie = new HttpCookie("myCookie");
    
    //Add key-values in the cookie
    myCookie.Values.Add("UserId", "your-UserId");
    myCookie.Values.Add("UrlSlug", "your-UrlSlug");
    
    //set cookie expiry date-time, if required. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddHours(12);
    
    //Most important, write the cookie to client.
    Response.Cookies.Add(myCookie);
    

    从cookie读取键值。

    //Assuming user comes back after several hours. several < 12.
    //Read the cookie from Request.
    HttpCookie myCookie = Request.Cookies["myCookie"];
    if (myCookie == null)
    {
        //No cookie found or cookie expired.
        //Handle the situation here, Redirect the user or simply return;
    }
    
    //ok - cookie is found.
    //Gracefully check if the cookie has the key-value as expected.
    if (!string.IsNullOrEmpty(myCookie.Values["UserId"]))
    {
        string UserId= myCookie.Values["UserId"].ToString();
        //Yes UserId is found. Mission accomplished.
    }
    
    if (!string.IsNullOrEmpty(myCookie.Values["UrlSlug"]))
    {
        string UrlSlug = myCookie.Values["UrlSlug"].ToString();
        //Yes key2 is found. Mission accomplished.
    }
    

    如果你需要的话 打扰 这个 身份验证cookie,尽管不是 建议你这样做。

    将键值写入cookie。

    //create a cookie
    HttpCookie myCookie = FormsAuthentication.GetAuthCookie("UserName", true);
    
    //Add key-values in the cookie
    myCookie.Values.Add("UserId", "your-UserId");
    myCookie.Values.Add("UrlSlug", "your-UrlSlug");
    
    //set cookie expiry date-time, if required. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddHours(12);
    
    //Most important, write the cookie to client.
    Response.Cookies.Add(myCookie);
    

    从cookie读取键值。

    //Assuming user comes back after several hours. several < 12.
    //Read the cookie from Request.
    HttpCookie myCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if (myCookie == null)
    {
        //No cookie found or cookie expired.
        //Handle the situation here, Redirect the user or simply return;
    }
    
    //ok - cookie is found.
    //Gracefully check if the cookie has the key-value as expected.
    if (!string.IsNullOrEmpty(myCookie.Values["UserId"]))
    {
        string UserId= myCookie.Values["UserId"].ToString();
        //Yes UserId is found. Mission accomplished.
    }
    
    if (!string.IsNullOrEmpty(myCookie.Values["UrlSlug"]))
    {
        string UrlSlug = myCookie.Values["UrlSlug"].ToString();
        //Yes key2 is found. Mission accomplished.
    }