How to save user data in ASP.NET Membership Cookie

Can someone give me an example (or point me in the right direction) on how to store user data in an ASP.NET membership cookie?

I need to add some user properties, such as UserID and URLSlug, to the cookie and be able to receive information in the same way as getting the username.

Edit:

I used the Code Poet example and came up with the following.

When I set a breakpoint in Dim SerializedUser As String = SerializeUser(userData) , the value of userData is correct. It has all the properties that I expect.

The problem that I am facing right now is that when I get to Dim userdata As String = authTicket.UserData (breakpoint), the value is "" . I would like to find out what I'm doing wrong.

Here is the code.

 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 

Here I create all the magic. This method is in the "BaseController" class, which inherits from 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 

And this is how I try to get the information.

  Dim user As Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser 
+4
source share
2 answers

Depending on the scenario, using a separate cookie may be a viable option, but, in my opinion, is optimal for several reasons, including the simple fact that you need to manage multiple cookies and also manage the lifetime of the cookie.

The most reliable strategy for including user information in your form form is to use the userData field for the ticket. That is exactly what it is.

You can easily save user data in the userData field of the ticket.

There are several questions you need to know about the amount of data that will be stored on the ticket, which are explained here.

And here is a small class that can help in the task of saving user data in a form ticket.

+4
source

First of all, ASP.Net membership providers do not write any cookies; authentication cookies are written to FormsAuthentication.

And secondly, why bother with the authentication cookie? You can do this in a separate cookie. Here is how you can do it.

Writing value keys to a 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); 

Reading value keys from a 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. } 

If you need to bother at all, the authentication cookie, although not advisable, can do so.

Writing value keys to a 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); 

Reading value keys from a 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. } 
+6
source

Source: https://habr.com/ru/post/1315616/


All Articles