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.
Related
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'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.
The website where I work is made up of several projects (written in several languages). Right now we have to use some awkward code in query strings and session variables to keep a person logged in when they go from project to project. Since cookies are domain specific we're trying to convert to them since they can be set in one project using one language yet be accessed by a different project (on the same domain) using a different language.
However I am having problems changing the value of a cookie and deleting them. Or to be more specific, I'm having trouble having any changes I make to a cookie stick.
For example in my logout code:
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie myCookie = new HttpCookie("thisuserlogin");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Set(myCookie);
litTest.Text = myCookie.Expires.ToString() + "<br />" + Request.Cookies["thisuserlogin"].Expires.ToString();
}
I wind up with one line being yesterday and the next line being 1/1/0001 12:00:00 even though they SHOULD be the same cookie. So why is it that even though the cookie was set, it's value did not change? Is there a way to force the user's computer to update a cookie's value, including deletion?
Thank you very much.
PS Any URLs you can provide to give an easy-to-understand primer for cookies would be appreciated.
http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie byeCookie = new HttpCookie("thisuserlogin");
byeCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(byeCookie);
// Update Client
Response.Redirect(Request.RawUrl);
}
You should use a tool like Fiddler on the client side to capture all of the data going back and forth. This will help you see that your cookie should be set with a date in the past (and missing from the next request too).
As for your textbox output, you're listing the cookie you created expire time and the expire time of the request cookie, which doesn't have one. If you were to look at the response cookie instead, you should see the date being set. Also, the call to Response.Cookies.Set is unnecessary. Response.Cookies.Add should be all you need.
I have a page where a user logs in to a back-end application via a web service. The web service returns a session ID which I want to store in a cookie for 40 minutes, as after 40 minutes the back-end application automatically closes the session.
My code to write the cookie:
private void SetCookie()
{
Response.Cookies.Add(new HttpCookie("Cookie_SessionID"));
Response.Cookies["Cookie_SessionID"].Value = ni.NicheSessionID;
Response.Cookies["Cookie_SessionID"].Expires = DateTime.Now.AddMinutes(40);
//.... after a few more things
Response.Redirect(returnUrl);
}
Then on the receiving page I have this:
private HttpCookie GetCookie()
{
HttpCookie cookie = Request.Cookies["Cookie_SessionID"];
if (cookie != null && cookie.Value != null)
{
return cookie;
}
return null;
}
For some reason the cookie returned by GetCookie() always has an Expires value of 0001-01-01 00:00:00, even though when I view cookies in the browser it has the correct expiry time.
Having read this which states expired cookies are simply not sent to the server, I assume what could be happening is that the cookie is being written correctly but the browser is not sending the expiry date because it's actually unnecessary?...
My problem is that I want to capture precisely that - the cookie has 'expired' and so they have to log in again - but I need to display a message along the lines of "I know you have already logged in but you'll need to do it again" type thing.
Thanks
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.
If you want to display such a message then you will need some other mechanism of detecting that the user was logged in. You might set a presence cookie for a year or so and check to see if it exists.
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.)
The HTTP protocol does not send cookie expiration dates to the server.
I need to revoke an authentication cookie if the user no longer exists (or some other condition), after the forms authentication mechanism already have received the authentication cookie from the browser and have validated it. I.e. here is the use scenario:
The user have been authenticated, and granted non-expiring auth cookie.
In a few days, the user tries to access my web app again, and as the cookie is valid, the forms authentication mechanism will grant access.
Now I want to perform a second check (whatever condition I want), and decide if I want to let the user continue, or to revoke the authentication.
The question is - is there an official automated way for this? So far I have come with some possibilities, but I do not know which one is better. I can capture the Authenticate event in global.asax, check whatever I want, and to revoke I clear the cookie, and then one of these:
Redirect again to same url - this should work, as this time the forms authentication will fail, and it will redirect to logon page.
Throw some exception ??? which one to make the redirect happen w/o me specifying anything?
Somehow to get the logon page url from the config file (any ideas how/which config handler to use) and redirect directly?
Some FormsAuthentication class/method I have overlooked, which is designed for this?
Any other idea?
I don't think there is an automated way to achive this.
I think the best way would be to add a date to the auth cookie which will be the last time you checked whether the user exists.
So when a user logs-in you'll:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
name, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMonths(1), // Date/time to expire
true, // "true" for a persistent user cookie
DateTime.Now.ToUniversalTime(), // last time the users was checked
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
cookie.HttpOnly = true;
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
//cookie.Secure = FormsAuthentication.RequireSSL;
Response.Cookies.Add(cookie);
Then everytime a user is authenicated you can check the additional date you passed to the Authentication ticket and in 10 minute intervals or less double check against the database whether the user exists.
The code might look something like this:
public void FormsAuthentication_OnAuthenticate(object sender,
FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(
Request.Cookies[FormsAuthentication.FormsCookieName].Value);
DateTime lastCheckedTime = DateTime.TryParse(ticket.UserData);
TimeSpan elapsed = DateTime.Now - lastCheckedTime;
if (elapsed.TotalMinutes > 10)//Get 10 from the config
{
//Check if user exists in the database.
if (CheckIfUserIsValid())
{
//Reset the last checked time
// and set the authentication cookie again
}
else
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
return;
}
}
}
catch (Exception e)
{
// Decrypt method failed.
}
}
}
}
You can even cache the users that have been deleted the last 10 minutes and check against that collection.
Hope that helps.
If you are rejecting the cookie for some other reason than an expired session, then I think you should redirect the user to a page that describes what they need to do in order to gain access. If logging on again is sufficient, then the logon page would suffice. It sounds, however, like there are conditions under which simply logging on again is not possible. In those cases, it would be better to redirect the user to a suitable error page that describes why they are unable to access the site and explains how to gain access again (if possible).