How can I simply update the expiry of a cookie on each page request without having any impact on its value ?
'update the User cookie expiration time on every page load
Dim cookieName As String = ConfigKeys.UserCookieName
Dim cookieExpr As String = ConfigKeys.CookieExpiration.ToString
'--get the cookies from request object
Dim userCookie As HttpCookie = HttpContext.Current.Request.Cookies(cookieName.ToUpper())
'--set the expiry date
userCookie.Expires = DateTime.Now.AddMinutes(Integer.Parse(cookieExpr))
'--add the updated cookies back to Response object
HttpContext.Current.Response.Cookies.Add(userCookie)
HttpContext.Current.Response.Cookies["MyCookie"].Expires =
DateTime.Now.AddDays(1)
Or set it to maximum and forget about the expiration:
HttpContext.Current.Response.Cookies["MyCookie"].Expires =
DateTime.MaxValue
Related
I wrote this code for my login page:
HttpCookie cookie = new HttpCookie("a");
cookie["name"] = (string)ddr["name"];
cookie["phone"] = (string)ddr["phone"];
cookie.Expires = DateTime.Now.AddSeconds(10);
How can I use the cookie expire time in other pages to block users after 10 seconds?
In my logout function, I have
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
I see that the response contains set-cookie for ASP.NET_SessionId with the proper expiration, but then the browser (Chrome in this case) never actually deletes the cookie.
tiy can try with this code
HttpCookie myCookie = new HttpCookie("ASP.NET_SessionId");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
I'm using a cookie containing an encrypted key to use for authentication. What i need is to delete this cookie on logout. As per msdn a cookie cannot be removed from a client's browser, so I tried to set expiry date HttpContext.Current.Request.Cookies["CAuthCookie"].Expires = DateTime.Now.AddDays(-1);, however the cookie remains. Any other ideas?
Try this:(place this in your logout code)
HttpCookie cookie = new HttpCookie("CAuthCookie", "");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(cookie);
I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserId,
DateTime.Now,
DateTime.MaxValue,
false,
user.UserType);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
However, when reading this back on the next Request, I found that the UserData field is now empty:
string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!
Any ideas?
I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
to
HttpCookie cookie = new HttpCookie(
"SiteCookie",
FormsAuthentication.Encrypt(ticket));
And then retrieve it as per the question:
string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works
Its possible .NET does some tricky stuff with it, so by putting it in a new one works fine.
UPDATE:
Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:
FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
I have also encountered this problem.
But I think the real reason is that the server set the same cookie twice and the second override the first which contains your UserData field.
You can capture the cookie writing process by Fiddler, and here is a screenshot that show this problem:
So, how this happened? In my situation, I use the Login control to authenticate. In the Login control's Authenticate event, I set the cookie with my UserData after check the username and password manaully. Then, I set the AuthenticateEventArgs.Authenticated=true, at this time, in the debug window, I see a new cookie is queued to the response which name is also equal to FormsAuthentication.FormsCookieName ! My solution is redirect to the Default page instead of setting the AuthenticateEventArgs.Authenticated=true.
So, you may debug your code to see if the authentication cookie is queued to the response twice.
This works for me:
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
I am creating a cookie in one page of an ASP.NET application and I want to delete it in another page. How do I do that?
Microsoft: How To Delete a Cookie
You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
To assign a past expiration date on a cookie
Determine whether the cookie exists in the request, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object of the Response.
The following code example shows how to set a past expiration date on a cookie.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Note: Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.
Have you tried expiring your cookie?
protected void btnDelete_Click(object sender, EventArgs e)
{
Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1);
}
How to: Delete a Cookie
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("MyCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
First you have to set the expiry date of the cookie to a previous date.
For Example :
HttpCookie newCookie = new HttpCookie("newCookie");
newCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(newCookie);
Now only doing this will not be helpful as the cookie will not be physically removed. You have to remove the cookie.
if (newCookie.Expires < DateTime.Now)
{
Request.Cookies.Remove("newCookie");
}
Here you go. This applies to any page within the solution.