asp.net delete cookie - asp.net

I'm using a cookie containing an encrypted key to use for authentication. What i need is to delete this cookie on logout. As per msdn a cookie cannot be removed from a client's browser, so I tried to set expiry date HttpContext.Current.Request.Cookies["CAuthCookie"].Expires = DateTime.Now.AddDays(-1);, however the cookie remains. Any other ideas?

Try this:(place this in your logout code)
HttpCookie cookie = new HttpCookie("CAuthCookie", "");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(cookie);

Related

Something wrong with cookies in asp.net

I am building a web application and when a user signs in, his credentials are first validated against the database. If the credentials are correct, a FormsAuthenticationTicket is created. Then a cookie is created from that ticket. The Expires and Path properties are set. See below.
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket(1, model.User.UserName,
DateTime.Now, DateTime.Now.AddHours(2), RememberMeCheckBox.Checked,
model.User.Id.ToString()+" "+model.User.UserType.ToString());
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
cookie.Expires=ticket.Expiration;
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
Response.Redirect("DummyForm.aspx");
And when I redirect the response to a new page, in the Page_Load event the presence of a cookie is checked.
HttpCookie cookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookiePath];
if(cookie!=null)
{
//Do stuff
}
else
{
//Do other stuff
}
When I run the application, it behaves like the cookie variable is null.
Is there something that I have omitted?
Thanks in advance for your help.
cookie.Domain="localhost";
cookie.Name="My auth cookie";
I also set the domain property to localhost in web.config. However, it still doesn't work. I used the developer tools of Google to check the cookie and I can't see it there.

Asp.Net Cookie does persists after browser closing

What i'm basically doing is creating a cookie and using form auth.
This is what i'm using to create the cookie.
Session.Add("username", userName);
Session.Add("password", passWord);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.Now.AddMinutes(1), false, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);`
Because i'm logging in to something secure, what I want to happen is when the browser closes to delete the cookie that this site creates. However, that doesnt happen, i'm able to log into the secure section of my site.
What am I missing?
basically if I log into /secure/secure.aspx and then close my browser, i can type in www.myaddress.com/secure/secure.aspx and i'll be logged in. I'm 100% positive that it will deny the user if the user has never logged in.
That behavior is controlled by the browser settings. You can control when the author cookie expires but now when its deleted from the client machine.
One strategy is to set the cookie to expire in X minutes on each request. That way if the user is inactive on the site for more than X minutes, they will have to login again.

Expiring asp.net session cookie

In my logout function, I have
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
I see that the response contains set-cookie for ASP.NET_SessionId with the proper expiration, but then the browser (Chrome in this case) never actually deletes the cookie.
tiy can try with this code
HttpCookie myCookie = new HttpCookie("ASP.NET_SessionId");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);

FormsAuthentication isn't preserving the UserData field after Postback in .NET 3.5

I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserId,
DateTime.Now,
DateTime.MaxValue,
false,
user.UserType);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
However, when reading this back on the next Request, I found that the UserData field is now empty:
string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!
Any ideas?
I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
to
HttpCookie cookie = new HttpCookie(
"SiteCookie",
FormsAuthentication.Encrypt(ticket));
And then retrieve it as per the question:
string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works
Its possible .NET does some tricky stuff with it, so by putting it in a new one works fine.
UPDATE:
Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:
FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
I have also encountered this problem.
But I think the real reason is that the server set the same cookie twice and the second override the first which contains your UserData field.
You can capture the cookie writing process by Fiddler, and here is a screenshot that show this problem:
So, how this happened? In my situation, I use the Login control to authenticate. In the Login control's Authenticate event, I set the cookie with my UserData after check the username and password manaully. Then, I set the AuthenticateEventArgs.Authenticated=true, at this time, in the debug window, I see a new cookie is queued to the response which name is also equal to FormsAuthentication.FormsCookieName ! My solution is redirect to the Default page instead of setting the AuthenticateEventArgs.Authenticated=true.
So, you may debug your code to see if the authentication cookie is queued to the response twice.
This works for me:
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);

How can I delete a cookie in a particular page?

I am creating a cookie in one page of an ASP.NET application and I want to delete it in another page. How do I do that?
Microsoft: How To Delete a Cookie
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.
To assign a past expiration date on a cookie
Determine whether the cookie exists in the request, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object of the Response.
The following code example shows how to set a past expiration date on a cookie.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Note: Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.
Have you tried expiring your cookie?
protected void btnDelete_Click(object sender, EventArgs e)
{
Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1);
}
How to: Delete a Cookie
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("MyCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
First you have to set the expiry date of the cookie to a previous date.
For Example :
HttpCookie newCookie = new HttpCookie("newCookie");
newCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(newCookie);
Now only doing this will not be helpful as the cookie will not be physically removed. You have to remove the cookie.
if (newCookie.Expires < DateTime.Now)
{
Request.Cookies.Remove("newCookie");
}
Here you go. This applies to any page within the solution.

Resources