How can I create persistent cookies in ASP.NET?
Asked Answered
H

6

79

I am creating cookies with following lines:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

Now how can I make it persistent?

If I visit the same page again after closing the browser, I'm unable to get it back.

Holmquist answered 29/6, 2010 at 11:52 Comment(0)
F
121

Here's how you can do that.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}
Furuncle answered 29/6, 2010 at 12:9 Comment(3)
Reading the persistent cookie code didn't work for me. See my answer in this post.Muleteer
Your code is functionally no different from that posted in the original question though except your cookie expires in 12 hours and OP's does in a year.Aldenalder
@Aldenalder As Chance points out, there is a key difference, the OP is adding to the default time of 0001/01/01 and this answer is adding to the current time.Refluent
L
62

Although the accepted answer is correct, it does not state why the original code failed to work.

Bad code from your question:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.

Corrected code:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
Lakendra answered 25/6, 2015 at 19:41 Comment(0)
P
30

FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}
Picayune answered 29/6, 2010 at 12:23 Comment(6)
Did he say FormsAuthentication cookie ? And why use var when you know the type.Furuncle
Thanks for security concern but I'm using encryption for the cookies!Holmquist
Because redundant specification of variables is redundant. And since the question specifically shows userid as the value to store in the cookie the FormsAuth cookie is the most correct solution for this IMO.Picayune
@KimJongWoo even without using forms auth for your application you could still use these functions to generate secure cookiesPicayune
don't i need to specify anything that this cookie is an authorizationCookie ?Doorman
@Doorman if i'm understanding your question right, cookies are just text. If your question is about the cookie being received by the ASP.NET Forms Authentication and working properly, that's handled by the FormsAuthentication.Encrypt(newTicket); it creates an encrypted serialized item that when the server gets it back decrypts it and hydrates the generic user identity model.Picayune
H
2

As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

HttpContext.Current.Response.Cookies.Add(authCookie);
Hastings answered 26/11, 2015 at 17:8 Comment(0)
T
0

You need to add this as the last line...

HttpContext.Current.Response.Cookies.Add(userid);

When you need to read the value of the cookie, you'd use a method similar to this:

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;
Theatrician answered 29/6, 2010 at 11:57 Comment(0)
M
0

//add cookie

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

//read cookie

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }
Muleteer answered 2/4, 2013 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.