Expire cookie at end of session OR at specific time? - c#

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.

Related

ASP.Net HttpCookie Expiration

If you set a cookie's expiration to DateTime.Now.AddDays(-1), when would it expire? It shows that the expiration is yesterday. Here is the code:
var rememberMeCookie = new HttpCookie("remember_me");
rememberMeCookie.Expires = DateTime.Now.AddDays(-1);
There is no HTTP Header to delete the cookie, when you click "Logout", this is a trick to confuse browser with previous expiration date, so browser will immediately delete cookie from its store.
This question is like you bought a milk on 11/09/2015 but expired on 10/09/2015, then you ask:" should i drink it?" Of cause not! because expired is 'YESTERDAY' like you said.
you cannot get anything from a expired cookie.

Extend forms authentication timeout dynamically

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);
}

set a expiration of cookies when inactive c#

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.

what is the default expiration time of a cookie

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).

.Net cookies keep coming back with expiration of zero

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.

Categories

Resources