Can't delete cookie in ASP.NET C# - 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

Related

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.

Why is my cookie showing as null in C# ASP.NET Empty Web Project?

Working on a Black Jack game and I am trying to save the Player's balance as a cookie. I cannot get it to work properly. When exiting the browser and reloading the webpage, the cookie is always null.
I declared the cookie as a static variable so I can access in a later method to send it to the client.
public partial class BlackJack : System.Web.UI.Page
{
public static HttpCookie cookie;
protected void Page_Load(object sender, EventArgs e)
{
cookie = Request.Cookies["Balance"];
if (!IsPostBack)
{
if (cookie != null)
{
PlayerBalance = Convert.ToInt32(cookie.Values["balance"]);
if (PlayerBalance == 0)
{
PlayerBalance = 250;
}
}
else
{
PlayerBalance = 250;
HttpCookie cookie = new HttpCookie("Balance");
cookie.Values.Add("balance", PlayerBalance.ToString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
PlayerBet = 0;
}
Then in a later method that runs after each hand, I save the cookie with Response.Cookies.Add().
public void Other Method()
{
cookie = Request.Cookies["Balance"];
cookie.Values["balance"] = PlayerBalance.ToString();
Response.Cookies.Add(cookie);
}
But if I close out of a browser and return to the site, the cookie is always null.
Cookies are non-persistent by default. That means as longas you don't specify an expiration date for the cookie the browser clears it, when you close the browser.
So in this case you'll need a persistent cookie, which can be created by setting the Expires-property:
var cookie = new HttpCookie("Balance");
cookie.Expires = DateTime.Now.AddDays(1);
For more details have a look at this comprehensive article: https://msdn.microsoft.com/en-us/library/ms178194.aspx
But note what #CodeCaster already said: A cookie is only a small piece of text which can be easily modified by the client. So you should consider storing sensitive information elsewhere. Or at least you should consider encrypting your cookies.
Remove the line
public static HttpCookie cookie;
It will create a non-thread safe type of cookie .In mutitreaded environment it will have mess up value.
This works fine..Your static causes the problem.Create cookie every every method and Dump it on browser Response.Cookies.Add(cookie) with same name
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("Balance");
cookie.Values.Add("balance", "akash".ToString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
protected void Button1_Click(object sender, EventArgs e)
{
var cookie = Request.Cookies["Balance"];
cookie.Values["balance"] = "ggg".ToString();
Response.Cookies.Add(cookie);
}

MVC Forms Authentication and Session, Authorize Issues

I have a MVC project that I'm using Forms Authentication, and I had to implement Roles for certain pages, so I got this in global.asax:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(';');
if (Context.User != null)
{
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}
}
And I save the user roles when I log in my model:
//After checking login/password
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie == null)
{
cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
HttpContext.Current.Response.Cookies.Add(cookie);
}
string userRoles = null;
if (users[i].PerfilID == UserRanks.Admin)
{
userRoles = "Admin;Users";
}
else
{
userRoles = "Users";
}
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0,
users[i].Name,
DateTime.Now,
DateTime.Now.AddDays(1),
false,
userRoles,
FormsAuthentication.FormsCookiePath
);
cookie.Value = FormsAuthentication.Encrypt(ticket);
HttpContext.Current.Response.Cookies.Set(cookie);
HttpContext.Current.Session["UserID"] = users[i].UserID;
HttpContext.Current.Session["LastLogin"] = users[i].LastLogin;
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, userRoles.Split(';'));
To retrieve the values of the session variables, I have a static property:
public static int UserID
{
get
{
object sessionData = HttpContext.Current.Session["UserID"];
if (sessionData == null)
{
//I had something here...
return 0;
}
return Convert.ToInt32(sessionData);
}
private set { }
}
Before I implemented roles authorization, I used to save the UserID in the cookie userData, and if the UserID in the session, when requested, was null, I'd retrieve it from the cookie instead (and set it to the session again).
Now the userData is being used to the roles management and I'm having issues with the session dropping faster than the cookie expiration, and I have users logged in which I can't retrieve their UserIDs and thus fails for all operations.
So I have to put a checker in each controller function such as:
if (MyUser.Session.UserID == 0)
{
//redirect to Login
}
...which defeats the whole purpose of using [Authorize] I guess.
Is there a better way to handle login expiration and session variables like this?
I thought about using JSON or some other format and save a bunch of userData in the cookie, but I'd like something simpler, if possible.
Also, I'm doing this in the login:
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, userRoles.Split(';'));
Which seems to be about the same the AuthenticateRequest does (I got that part from elsewhere, seemed to be the recommended way to handle member roles), but it doesn't work like it should. The user always gets redirected out on the [Authorize(Roles="Admin")] or even the [Authorize] only functions if I leave only that (and remove the global.asax part). Why?

ASP.net MVC FormsAuthentication cookie missing

I'm writing an ASP.net MVC 5 application using FormsAuthentication. I had everything up and working properly using FormsAuthentication.SetAuthCookie(user.Email, model.RememberMe).
However, I wanted to create a custom ticket so I could store some extra information in the UserData field of the ticket. This is how I'm creating my ticket and storing it in a cookie:
var ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), model.RememberMe, user.AuthToken);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath, HttpOnly = true, Secure = FormsAuthentication.RequireSSL };
HttpContext.Response.Cookies.Add(cookie);
This creates an encrypted ticket and sends it to the browser. I've verified with developer tools and Fiddler that the ticket is present in the browser and that it is sent back to the server on the subsequent requests.
But authentication is now broken. Also, the cookie is not available in Application_AuthenticateRequest or Application_PostAuthenticateRequest events. When I use the debugger to explore Context.Request.Cookies it is not present in the list.
Oddly enough the cookie does exist if I step back in the pipeline and check it in Application_BeginRequest:
void Application_BeginRequest(object sender, EventArgs e)
{
// Auth cookie exists in the collection here! Ticket decrypts successfully
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
}
void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Auth cookie missing from the cookies collection here!
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
using (var db = new BadgerContext())
{
var user = db.Users.OfType<RegisteredUser>().FirstOrDefault(x => x.UserName == ticket.Name);
if (ticket.UserData != user.AuthToken)
{
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.DefaultUrl);
}
}
}
So it appears that something is stripping my custom FormsAuthenticationTicket out of the cookies after BeginRequest but before AuthenticateRequest. Unfortunately, this breaks authentication altogether on the site.
Any ideas what is causing this behavior when I create a custom ticket? Am I doing something wrong with my cookie creation?
Check in the .config file the inside the system.web node, the httpRuntime tag.
<httpRuntime targetFramework="4.5" />
as same as main web site
Rowan suggested I look at the value for FormsAuthentication.Timeout.Minutes. After investigation, this value always came back as 0. This led to an immediate expiration of the ticket. I had to use FormsAuthentication.Timeout.TotalMinutes instead and everything started working properly

Cookie expiration issue in asp.net

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

Categories

Resources