rookie
rookie

Reputation: 401

Delete cookie on clicking sign out

I am creating the cookie using the code below, How to read the txtusername value in another page and how to delete the cookie when I click sign out(code for sign out). I am new to programming please help.

  string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
            DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
            cookiestr = FormsAuthentication.Encrypt(tkt);

            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            if (chkPersistCookie.Checked)
                ck.Expires = tkt.Expiration;
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

Upvotes: 9

Views: 28243

Answers (4)

Ava
Ava

Reputation: 838

In my case this code worked:

Response.Cookies.Delete("access_token");
return Ok();

Upvotes: 1

w00ngy
w00ngy

Reputation: 1828

FYI this did not work for me using Chrome 69 with the Continue where you left off feature enabled. Similar issue with Firefox. Disabling this feature worked for me.

See

Upvotes: 0

kakridge
kakridge

Reputation: 2293

You should never store password as a cookie. That's a very big security threat. To delete a cookie, you really just need to modify and expire it. You can't really delete it, i.e. remove it from the user's disk. Check out this documentation.

Here is a sample:

 HttpCookie aCookie;
    string cookieName;
    int limit = Request.Cookies.Count;
    for (int i=0; i<limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
        Response.Cookies.Add(aCookie); // overwrite it
    }

Upvotes: 14

Oskar Kjellin
Oskar Kjellin

Reputation: 21900

You cannot directly delete a cookie, you have to set it to expire before the current date:

if (Request.Cookies["clienDetails"] != null)
{
    HttpCookie myCookie = new HttpCookie("clienDetails");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

You can read more about it here.

Furthermore I really encourage you to not write your own security but to read up on asp.net membership. More secure and easier to use. As I can see many flaws in your security model. Storing the password in plain text in a cookie is really really bad.

EDIT: As you now changed your code, you have to do this to remove the cookie:

if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
    HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

Upvotes: 7

Related Questions