Problems erasing HTTP Cookie - c#

I have a cookie which stores user info like username, companID etc.
I need to be able to update the cookie if the user logs off and back on using a different account.
The problem I have is that I can't get rid of the previous details. I am expiring the cookie and then trying to give it a new company ID which it will then use to collect the user details but it won't overwrite it.
if (Request.Cookies["UserInfo"] != null)
{
HttpCookie myCookie = new HttpCookie("UserInfo");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
UserInfo.Values.Add("CompanyID", Convert.ToString(ds.Tables[0].Rows[0]["ID"]));
Response.Cookies.Add(UserInfo);
Now after this the cookie still stored the old details with old company ID.

Related

How do I set cookie expiration to session in C#

I am creating a website, and I'm not sure how to use sessions with cookies.
When sessions timeout, I want to show the username and time of the user; for e.g., username stored in cookies and session. When sessions timeout the username must be retrived from the cookies.
Lets put things in perspective first.
A session is the session a user is experiencing when he is using the website.
How it works is basically a user starts a session with the web server, the web server then gives it a key of the session and sets a timeout for the session which are stored as a cookie.
Since this process is automatic and you can only configure it in web.config (unless you are asp.net core vNext, which I doubt) with sessionState https://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.80%29.aspx
A normal HttpCookie on another hand is something you set on your Response object and can give it a specific expiration date like this:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Which suits your needs more likely.
If you want more information about sessions expiration I'd also suggest you check out http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx

c# Update Cookie, without forcing the user to login

I have a 'UI' setting that controls the appearance, which the user can change the setting, however it involves updating the cookie.
I seem to be able to update, but it forces the user to authenticate again, how can i update the cookie without getting the user to autenticate again?
//We need to update the userToken as the menuOptionChanged
var usertoken2 = new UserToken(schedule.MinimisedMenuBool);
HttpCookie cookie = FormsAuthentication.GetAuthCookie(usertoken.UserName, false);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newticket = new FormsAuthenticationTicket(ticket.Version,ticket.Name,ticket.IssueDate,ticket.Expiration,false,usertoken2.CalculateRawToken(),ticket.CookiePath);
// Encrypt the ticket and store it in the cookie
cookie.Value = FormsAuthentication.Encrypt(newticket);
System.Web.HttpContext.Current.Response.Cookies.Set(cookie);
Why are you saving UI appearance preferences in the authentication cookie?
Is there anything wrong with just saving it as a separate cookie?
HttpCookie menuCookie = new HttpCookie("menuCookie");
menuCookie.Values.Add("menuAppearance", schedule.MinimisedMenuBool);
menuCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(menuCookie);
Then you can optionally only parse that cookie for logged in users.

Session lost after login

On my website
Filling form before login save data in Session
Login Using Linkedin ID
after login at Pageload taking data from session then inserting into SQL data base
My problem is some times I am getting session and other times I am not getting session (Session Lost) ( mostly when 3-4 people testing at the same time... 2-3 get session and 1-2 not getting session)
Can any one tell me what is the problem? How can I solve this problem?
Any another way to do this task?
Stroing in session before login
Session["sesObjFundRaiseSeek"] = objFundRaiseSeek;
Getting after login
if (Session["sesObjSellSeekBL"] != null)
{
clsSellSeekBL ObjSellSeekBL = (clsSellSeekBL)Session["sesObjSellSeekBL"];
}
Is it a problem with your sessions timing out after a very short period of time? You can input the default session timeout within the web.config. This is done right under system.web. Here is an example where 480 is the number of minutes:
<sessionState timeout="480"></sessionState>
For more information: http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.71).aspx
An alternate solution is to use Cookies. I would recommend using Cookies to store user state information. Since Cookies are stored on the users computer, it is easier to configure:
I set to expiration date to 100000 days later in the example below:
HttpCookie myCookie = new HttpCookie("sesObjSellSeekBL");
myCookie.Value = Convert.ToString(user_id); //store the user id here at the very least
myCookie.Expires = DateTime.Now.AddDays(100000d);
Response.Cookies.Add(myCookie);
Here is how you check your Cookie:
if (Request.Cookies["sesObjSellSeekBL"] != null)
Here is how you log the user out:
HttpCookie myCookie = new HttpCookie("sesObjSellSeekBL");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);

How to remove all expired cookie from CookieCollection?

How to remove all expired cookie from a CookieCollection ?
Try this.
var cookies = Request.Cookies;
foreach (HttpCookie cookie in cookies)
{
if (cookie.Expires < DateTime.Now)
{
Request.Cookies.Remove(cookie.Name);
}
}
Please note the excerpt from MSDN,
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.
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.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1);//add -1 days
Response.Cookies.Add(myCookie);
}
The way you remove a cookie is to change it expire date to some thing that has already passed.. but a expired cookie should never be sent from the browser in the first case...

Check if currently logged in user has persistent authcookie

I need to edit userdata in an a FormsAuthentication AuthCookie of the currently logged in user. I don't see how to find out if the current user has chosen a persistent cookie ("Remember Me").
//user is already logged in...
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, ispersistant); //how to I determine 'ispersistant'?
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, NEWuserdata);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
HttpContext.Current.Response.SetCookie(authCookie);
Anybody got any ideas?
Thanks
The FormsAuthentication.GetAuthCookie method only creates a new cookie. It does not get you the earlier made cookie.
On your login page you probably have something like this:
FormsAuthentication.GetAuthCookie (userID, chkPersistCookie.Checked)
And to know when the user is authenticated you can do
this.Context.User.Identity.IsAuthenticated
I actually don't know for sure if you can deduce the fact that the user has a persistent auth cookie. One thing is checking the cookie for a expiry date.
In this question there is a example for reading the authentication cookie.
This should retrieve the existing forms auth cookie, examine the ticket, and tell if it's persistent.
var FormsAuthCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
var ExistingTicket = FormsAuthentication.Decrypt(FormsAuthCookie.Value);
bool IsPersistent = ExistingTicket.IsPersistent;
I ended up storing "ispersistant" in the userdata property of the authcookie on login.

Categories