Modifying cookie subkeys in C# - c#

I can't for the life of me understand what I'm doing wrong here. I've searched high and low but everything I try doesn't seem to fix.
I'm trying to create a cookie that stores the first and last name of a user. If the user goes back and changes either the first or second name it should modify these subkeys in the userName cookie. This part doesn't seem to work though?
protected void btnContinue_Click(object sender, EventArgs e)
{
if (IsValid)
{
HttpCookie cookie = new HttpCookie("userName");
if (cookie != null)
{
Response.Cookies.Remove("userName");
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
else
{
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
cookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Order.aspx");
}

The way to delete cookies on the client browser is to override them, setting the expires value to a date in the past.
When you use this code:
Response.Cookies.Remove("userName");
you only delete the cookie on server, which Means it's not sent to the client. This Means the old cookie on the client is kept.
To delete the old cookie:
HttpCookie cookie = new HttpCookie("olduserName");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
Here 'oldusername' contain the previous value of 'username'.
Edit:
Another way is to name your cookie with a name that doesn't change, ever, then you can simply override it with the new value, when username changes.
Edit2:
I actually made the same mistake as you did, you should use:
Response.Cookies.Set(cookie);
When using Add there can be more than one Cookie with the same name. This is most likely your problem (sorry, I did not see that before).
Edit2:
Just saw this line now:
Response.Redirect("~/Order.aspx");
You are redirecting! Then the cookies are not set on the client.
Instead you should set the cookies in "~/Order.aspx".

Related

HttpListenerResponse adding a 2nd cookie makes all cookies disappear

I have the following code:
void WriteConnectionId(HttpListenerContext context, string id)
{
var cookie = context.Response.Cookies[CookieConnectionId];
if (cookie == null)
{
cookie = new Cookie(CookieConnectionId, id)
{
HttpOnly = true,
Secure = true,
Path = "/"
};
context.Response.Cookies.Add(cookie);
}
else
{
cookie.Value = id;
}
//context.Response.SetCookie(new Cookie("lalala", "lololo"));
}
This code stores correctly the cookie for "connection Id" in the client. In Chrome's console I can see the cookie in the list of cookies.
However, if I uncomment the last line that adds an extra cookie, then neither the session cookie or the dummy cookie make it to the client. They do not appear in Chrome's console.
Edit: removing the "/" path on the first cookie makes the first cookie appear, though with both values from the 1st and 2nd cookie concatenated with a comma.
Try
context.Response.AppendCookie(new Cookie("lalala", "lololo"));
I ended up fixing this issue by creating the following function:
void FlushCookie(HttpListenerContext context, Cookie cookie)
{
var builder = new StringBuilder();
builder.Append(cookie.Name);
builder.Append("=");
builder.Append(HttpUtility.HtmlAttributeEncode(cookie.Value));
builder.Append(";");
context.Response.Headers.Add(HttpResponseHeader.SetCookie, builder.ToString());
}
This can be modified further to add cookie expiration, path, etc.

How to immediately remove cookies from browser

I am using cookies for my website.
I need to remove cookies immediately from browser for that i use this Code in C#
Code for removal of cookie
Response.Cookies["OptDepth"].Expires = DateTime.Now.AddYears(-30);
after execution of this code if i use this code
Code to check value of deleted cookie
Request.Cookies["OptDepth"].value;
then it gives me the value of specified cookie.
I need to remove cookies immediately from browser.
How can i do this.
If we change the name of that cookie with null then it works.
Code
Request.Cookies["OptDepth"].Name = null;
Now problem is solved.
Use Simple Code to replace cookies with expiry date:
if (Request.Cookies["OptDepth"] != null)
{
HttpCookie myCookie = new HttpCookie("OptDepth");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Here is an msdn detail link.Cookies
When adding a cookie ;
HttpCookie cookie = new HttpCookie("try");
cookie.Values["foo"] = "foo";
DateTime date = DateTime.Now.AddSeconds(-30);
cookie.Expires = date;
Response.Cookies.Add(cookie);
When Reading the cookie;
HttpCookie cookie = Request.Cookies["try"];
You will see the cookie is null.

Do I have to rewrite cookie everytime I postback to retain it?

I don't really understand the difference between request cookie and response cookie. And it seem like everytime I postback, if I don't manually rewrite the cookie from request to response, then it disappears. How do I solve this?
public string getCookie(string name) {
if (Request.Cookies["MyApp"] != null && Request.Cookies["MyApp"][name] != null) {
return Request.Cookies["MyApp"][name];
} else if (Response.Cookies["MyApp"] != null && Response.Cookies["MyApp"][name] != null) {
return Response.Cookies["MyApp"][name];
} else {
return "";
}
}
public void writeCookie(string name, string value) {
Response.Cookies["MyApp"][name] = value;
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
Request.Cookies["MyApp"];
Code above will return you a cookie with name "MyApp" Doing this:
Request.Cookies["MyApp"][name]
You are taking value "name" from cookie called "MyApp".
But in your setCookie code you are setting a cookie with called name and do not create a cookie called "MyApp":
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
So, you should remove ["MyApp"] from any place you have it, or you may do something like this in setCookie:
public void writeCookie(string name, string value) {
if(Response.Cookies["MyApp"] == null) {
HttpCookie newCookie = new HttpCookie("MyApp");
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
if(Response.Cookies["MyApp"][name] == null)
Response.Cookies["MyApp"].Values.Add(name, value);
else
Response.Cookies["MyApp"][name] = val;
// or maybe simple Response.Cookies["MyApp"][name] = val; will work fine, not sure here
}
Request is the "thing" you get when the user tries to get to your website, while Response is a way of responding to this request.
In other words, see the official msdn documentation, namely this part:
ASP.NET includes two intrinsic cookie collections. The collection
accessed through the Cookies collection of HttpRequest contains
cookies transmitted by the client to the server in the Cookie header.
The collection accessed through the Cookies collection of HttpResponse
contains new cookies created on the server and transmitted to the
client in the Set-Cookie header.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx
So no, you don't have to create new cookies every time, unless they have already expired. Just be sure you reference the right collection of cookies.
You might want to check the domain and path that are being assigned to the cookie. It could be that your saved cookies are just being orphaned because the path is too specific or because the wrong domain is being set.
Domain is the server name that the browser sees such as "yourdomain.com". If the cookie is set with a different domain than this then the browser will never send it back. Likewise, the path of the cookie is the path to the resource being requested such as "/forum/admin/index" etc. The cookie is sent for that location and all child locations, but not for parent locations. A cookie set for "/forum/admin/index" will not be sent if you're accessing a page that sits in the "/forum" directory.

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)

Cookies and session in asp.net

I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
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);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];

Categories