Cookie expiration issue in asp.net - c#

I am creating a cookie and getting a textbox value in it.I need to expire it and then has to print a message by checking that it has been expired or not.I am doing as following
HttpCookie usercookie = new HttpCookie("userinfo");
Response.Cookies["gettingusername"].Value = textbox_username.Text;
Response.Cookies["gettingusername"].Expires = DateTime.Now;
Response.Cookies.Add(usercookie);
if (Request.Cookies["gettingusername"]!=null)
{
Response.Write("Cookie is Not Expired");
}
else
{
Response.Write("Cookie Expired");
}
But it always says:-
Cookie is Not Expired
I am newbie for it.Please help.
Thanks in advance.

You can do it like below:
myCookie.Expires = DateTime.Now.AddDays(-1);
if(myCookie.Expires > DateTime.Now)
Response.Write("Cookie not Expired");
else
Response.Write("Cookie Expired");

Browser is responsible for removing expired cookies. You just need to set time in the future that it will expire. For example :
if (Request.Cookies["gettingusername"] != null)
{
Response.Write("Cookie is not expired")
Response.Write("Value exists : " + Request.Cookies["gettingusername"]);
}
else
{
Response.Write("Cookie is expired, creating a new cookie.");
Response.Cookies.Add(new HttpCookie("gettingusername")
{
Value = textbox_username.Text,
Expires = DateTime.Now.AddDays(1)
});
}

Try the following...
if (Request.Cookies["gettingusername"] != null)
{
HttpCookie myCookie = new HttpCookie("userinfo");
myCookie.Expires = DateTime.Now.AddDays(-1);//add -1 days
Response.Cookies.Add(myCookie);
}

Can't understand exactly what are you trying to achieve by that.
You should set them and check if they are expired in different methods.
For example, you can set cookie when press 'Set cookie' button and expire them in action 'Expire Cookie'

This is how you can delete your cookie Now..!
Response.Cookies["MyCookie"].Expires = DateTime.Now.AddDays(-1);

Related

How to maintain FormsAuthentication Cookie it's not deleting in MVC?

I have getting issue with delete FormsAuthentication ticket cookie with remember me option.. it always showing expired date 01/01/0001, I am setting FormsAuthentication ticket with expired time at the time of login controller.
When the application URL open that time again check the expired time & Auth Cookie.
everytime it Authentication cookies expired time showing the same..
How to manage FormsAuth ticket with remember me option?
I have search a lots in different forums but not get the exact solutions..
Below screenshot when i have not selected Remember me.
When I selected remember me it showing time in Expire age. but not handling with C# code.
// Here u is view model object that set the username,password and remember me options.
// LOGIN FUNCTION CODE
if (u.RememberMe)
{
int timeout = u.RememberMe ? 525600 : (int)sessionSection.Timeout.TotalMinutes; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(1, u.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(timeout), u.RememberMe, logmodel.UserType);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Path = FormsAuthentication.FormsCookiePath;
//cookie.Expires = System.DateTime.UtcNow.AddMinutes(timeout);// Not my line
//if (ticket.IsPersistent)
// cookie.Expires = ticket.Expiration;
cookie.Expires = ticket.Expiration;
/// cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
else
{
FormsAuthentication.SetAuthCookie(u.Email, false);
}

ASP.Net MVC 5 Cookie loses expiration upon return from the browser

This simple code has left me perplexed.
From this controller action method, I create a cookie , give it an expiration and set it to be HttpOnly. The cookie gets created correctly, added to the Response, looks correct on the browser debugger , however when returned back into the same code after refresh , loses expiration and HttpOnly flag. The cookie itself is still there , but the values are lost. If I watch Request.Cookies["mycookie"] back into the same controller/action method after a trip to the browser, the values are gone - the cookie itself is not deleted though.
If somebody understands this behaviour please explain, what might be happening here-
public class HomeController : Controller
{
public ActionResult Index()
{
if (this.ControllerContext.HttpContext.Request.Cookies["mycookie"] == null)
{
HttpCookie cookie = Response.Cookies["mycookie"];
cookie["mycookie"] = "test";
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
this.ControllerContext.HttpContext.Response.SetCookie(cookie);
}
return View();
}
The problem is this line: return View();
The cookie cannot be set and then read again (server-side) in the same round trip to the server. So, you need to create a second request for the cookie to be available. The simplest way is to force a second request by calling RedirectToAction, although you could use some clever AJAXy way of doing it so it appears to be the same request.
See this post for a working example - here is the part where the cookie is written and deleted.
public class CookieController : Controller
{
public ActionResult Create()
{
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
return RedirectToAction("Index", "Home");
}
public ActionResult Remove()
{
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
cookie.Expires = DateTime.Now.AddDays(-1);
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
}
return RedirectToAction("Index", "Home");
}
}
Ashiquizzaman is also correct in that you are not setting the value of the cookie, but that is only half of the problem.
Please see this code below.
var request=this.ControllerContext.HttpContext.Request;
var response =this.ControllerContext.HttpContext.Response;
//OR
// var request=System.Web.HttpContext.Current.Request;
//var response =System.Web.HttpContext.Current.Response;
if (request.Cookies["mycookie"] == null)
{
HttpCookie cookie= new HttpCookie("mycookie");
cookie.Value = "test";//your problem hear.
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
}
else//need to update your cookies then use this block or not
{
HttpCookie cookie=Request.Cookies["mycookie"];
cookie.Value = "test";//your problem hear.
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
//response.Cookies.SetCookie(cookie);
response.Cookies.Set(cookie);//To update a cookie, you need only to set the cookie again using the new values.
}
Hopefully it's help you.

SetPrincipal (#User.Identity.Name) from a cookie in ASP.Net MVC

I like to know how I can set the #User.Identity.Name via a cookie when a user clicks on a remember me checkbox.
Cookie code
if (_model.RememberMe)
{
HttpCookie cookie = new HttpCookie("login");
cookie.Values.Add("username", _model.Username);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
First login code
if (Membership.ValidateUser(Username,Password))
{
RememberMe();
FormsAuthentication.RedirectFromLoginPage(Username, false);
}
On the first login the Identity.name is set but when I close the browser and go back on to the site. it logs in correctly without the user putting in their credentials but the Identity.name is empty.
if (Request.Cookies["login"] != null)
{
// We know the automatic log in has worked as it comes into here...
}
What do I need to do once the user by passes the login page so I can setup the iPrincipal object?
Thanks
Try below code please
Note : please check it on page view not in the same method on creation of cokies
private void CreateCokies(string userName)
{
var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), true, userName);
string cookieContents = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
}

Can't delete cookie in ASP.NET C#

I've got a logout.aspx that is called when the user clicks logout and there is where I want to delete the cookies but it just won't do it...
public partial class LogoutUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie == null)
{
cookie = new HttpCookie("Basket");
}
foreach (string item in cookie.Values.AllKeys)
{
Response.Cookies[item].Expires = DateTime.Now.AddDays(-1);
}
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies["Basket"].Expires = DateTime.Now.AddYears(-1);
Session.Abandon();
Response.Redirect("~/Default.aspx");
}
}
The cookie stores the values in the basket but after logging out I can still access the basket I don't know what's wrong.
Here is some relevant documentation.
I believe your mistake is in this line:
if (cookie == null)
You're checking for null, rather than checking for not null. Thus,
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie != null)
{
cookie = new HttpCookie("Basket");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Default.aspx");
should do the trick.
Hope this is helpful.
Could it be this ?
Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId attribute of the sessionState configuration element to true. For more information, see Session Identifiers.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx

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);
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
}
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);
}
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
Chrome doesn't delete session cookies
How to delete or expire a cookie in Chrome using Asp.Net
In my case this code worked:
Response.Cookies.Delete("access_token");
return Ok();

Categories

Resources