Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cookie - Expires property won't set

Tags:

c#

.net

cookies

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

like image 211
Arj Avatar asked Dec 29 '11 15:12

Arj


2 Answers

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

like image 74
cdhowie Avatar answered Nov 12 '22 02:11

cdhowie


The HTTP protocol does not send cookie expiration dates to the server.

like image 20
SLaks Avatar answered Nov 12 '22 03:11

SLaks