By default what will be the expiration time of a cookie added using C# code?
HttpCookie myCookie= new HttpCookie("myCookie");
myCookie.Value = txtCookie.Text;
// Add the cookie.
Response.Cookies.Add(myCookie);
The default Expires value for a cookie is not a static time, but it creates a Session cookie. This will stay active until the user closes their browser/clears their cookies. You can override this as required.
From the linked page:
Setting the Expires property to MinValue makes this a session Cookie,
which is its default value
20 minutes.
In IIS, click on your website, and go to Session State. In the second box (Cookie Settings), you can change the time out(in minutes).
Related
I am not sure how that forms authentication. But I assume it just creates cookie based on forms authentication timeout.
So given that I am trying to increase forms auth cookie expiration based on some headers sent to server. For that I disabled slidingExpiration in order to calculate expiration on my own.
In Application_BeginRequest I am doing:
if (!bypassSlidingExpiration)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
authCookie.Expires = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
Response.Cookies.Add(authCookie);
}
But regardless of bypassSlidingExpiration my session expired after FormsAuthentication.Timeout.
What I am going wrong here?
What are you doing the other code branch? It looks like you're only handling the case where bypassSlidingExpiration is false. If bypassSlidingExpiration is true, then you're taking the default value (30 minutes, or whatever's specified in the web.config or programmatically).
You could consider using FormsAuthentication.SetAuthCookie(username, true) to bypass the sliding expiration. The second parameter is whether the cookie should be persistent. It's probably best to avoid manipulating the cookie manually. If you for some reason you must, something like this might work:
if (bypassSlidingExpiration)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
authCookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(authCookie);
}
i have this cookies
HttpCookie cookie2 = new HttpCookie("AuthorID", data.AuthorID.ToString());
cookie.Expires = DateTime.Now.AddMinutes(1);
HttpContext.Response.AppendCookie(cookie2);
is there a possible way to set a time of expiration when cookies is inactive of the user of the site is not doing anything? for example reloading the page etc.
what i did is set a time for 1 min and its not working does anybody know?.
i'm having trouble i have search in the internet but i didn't find any useful advice
I implemented something similar in my project.
Process:
For each request send a cookie.
On client side write a JavaScript code for reading the cookie when the page is loaded.
In JavaScript check the expiration date of the cookie.
If the cookie as expired (or not present) do your actions for inactive users (e.g. reload the page, display a message, disconnect him...).
You may also slightly change the above scenario like:
Set expiration date/time as cookie value.
Idem
Make sure cookie value < current date/time
Idem
If you care about users rejecting cookies you can do it in JavaScript without cookies. For example:
Set JavaScript variable 'lastActionTime'.
Create methods checking that 'lastActionTime' > time + delay
Attach common JavaScript events (clicks, focus...) and once called set 'lastActionTime' to the current time.
I am having trouble with the .Expires cookie attribute. It keeps coming back with 01/01/0001 12:00 AM, when I read the cookie back.
Here is the code. I added in the retrieve just below the save solely for debugging purposes. The save and retrieve happen in different places in the same file. I purposely did not specify a Domain, as I want the cookie to exist site wide.
The data shows up nicely, just not the expiration.
Note: I am testing under Visual Studio 2012 running under local host using .Net Framework 4.
System.Web.UI.Page oPage = this.Page;
HttpCookie oCookie = new HttpCookie("UserData");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Field1"] = strField1;
oCookie["Field2"] = strField2;
oCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie.
oPage.Response.Cookies.Add(oCookie);
// Get the cookie.
oCookie = new HttpCookie("UserData");
oCookie = oPage.Request.Cookies["UserData"];
The browser will not send anything to the server except the cookie name and value. All of the other properties (expires, domain, path, httponly, ...) cannot be retrieved on requests after the cookie has been set.
The more accepted way to deal with this is to redirect the user to a login page when they try to access a protected resource and display some message along the lines of "You need to log in to view this page. If you were previously logged in, your session may have expired."
(Also note that you should be re-setting the cookie on every request, so that the user will not be logged out if they continue to use the site. It's not clear from your code whether you are doing this or not.)
I was just doing some more Google searching on my problem and saw this link, another posting here on Stackoverflow.
Cookies are always expired
I am also validating using the construct:
if (cookie != null && cookie.Expires > DateTime.Now)...
As several pointed out, expiration checking happens, if you can no longer retrieve the cookie. That is seriously dumb on whomever constructed this architecture. Yes, maybe there should be RequestCookie and ResponseCookie, the difference being ResponseCookie has no Expiry date.
The person who resopnded to me taught me that it is not just expires but other fields too.
In C# code, if using Form Authentication, You can find if cookie is persistent using below code
bool IsCookiePersistent = ((FormsIdentity)User.Identity).Ticket.IsPersistent;
Here Ticket will return the FormsAuthenticationTicket which has Expiration DateTime property.
I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
HttpCookie myCookie = new HttpCookie("loginidcookie");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");
So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you
Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
var myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);
Note (from here):
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.
You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");
Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.
Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.
Is it possible to have a cookie expire at the end of a session, or at a specific time?
Yep! It's simple
HttpCookie newCookie = new HttpCookie("myCookie");
newCookie.Expires = DateTime.Today.AddDays(1);
If you want the cookie to be for the session, set it to DateTime.MinValue. See the MSDN Documentation here for more info. Here's the excerpt:
Setting the Expires property to MinValue makes this a session Cookie,
which is its default value.
since this is not possible with a single cookie i am sending two cookies. the auth cookie expires at the end of the session. the second cookie expires at a specific time. on each request i check the second cookie and if it is null i log the user out manually.
You can control cookie life time with Expires and Max-Age properties. Anyway if session is expired or you invalidate it impliclty, cookie associated with this session (for example jsessionId) are not valid anymore.