Reputation: 9
I need to make a cookie, which does send/read whenever the user called User1(and only by this user) does open the website. It should contain, that after the User1 is logged in it should never log him out again even when he does close the browser.(so when he reopens the Browser and the site, he should still be logged in. Does anyone know how i could approach this? I would really appreciate if you would give me some code which is commented due the fact, that i am not very into all of these things and really would like to understand what you guys did.
The cookie is needed for an internal web-application so it is not manditory that its password needs to be encrypted. if you think about a "remember me" like solution.
(languages are aspx and VB.)
thanks in advance
Upvotes: 0
Views: 37
Reputation: 1091
Detecting the user that has accessed the website is something that I will assume you already know so I will not go over this any further. Once you have identified the user you can create and send a custom cookie, you set the cookie timeout at a valid date and time for expiration. While you can set the expiration as far forward into the future as you like there are some browsers that may ignore it, also some older browsers require your cookies to have a privacy policy set (see Create a compact privacy policy). In the example below the code DateTime.Now.AddMinutes(30)
defines the expiration date, that is the bit you will need to set well into the future.
The forms authentication Ticket object is well documented here: http://support.microsoft.com/kb/910443
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
UserName, _
DateTime.Now, _
DateTime.Now.AddMinutes(30), _
False, _
"", _
FormsAuthentication.FormsCookiePath)
' Encrypt the ticket.
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
' Create the cookie.
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
Upvotes: 0
Reputation: 109005
If you are using the ASP.NET membership system, then the current user's username is Membership.GetUser().UserName
(see here and here) so that's easy to check. Remember that unless all paths to the page require login, there may not be a current user.
To set a cookie, add it to the Response.Cookies
collection.
Edit: additionally, to avoid issues when the user logs out, if not the specific user explicitly remove the special cookie from Response.Cookies
.
Upvotes: 1