C# multi-value cookies not working - c#

Hi I am creating a cookie in the following way:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie.Values["test1"] = "Value1";
cookie.Values["test2"] = "Value2";
cookie.Values["test3"] = "Value3";
//I have also tried cookie.Values.Add("test1", "Value1");
cookie.Expires = DateTime.Now.AddDays(365d);
HttpContext.Current.Response.AppendCookie(cookie); //here I have also tried HttpContext.Current.Response.Cookies.Add(cookie);
but when I read out the cookie using the following code:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie = HttpContext.Current.Response.Cookies["CookieNameHere"];
I always get that the cookie.Values is empty
Is there something I am doing wrong here?

Normally you would write the cookie in a Response, and then read it from subsequent Requests.
I see you're trying to read it from the Response - is this within the context of the same HTTP request, or just a typo?
Try
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieNameHere"];

You have to ask for those Cookies in a Request.
HttpCookie cookie = Request.Cookies["CookieName"];

Related

Cookie reading value is null

I am using VS2015, C#.
My cookie value is:
Provider=Custom&Email=someemail#gmail.com&UserName=John&FirstName=Test&LastName=LastTest&Expires=11.7.2016
11:03:05
I am trying to get this value with:
HttpContext context = HttpContext.Current;
HttpCookie cookie = context.Request.Cookies["Login"];
string provider = cookie["Provider"];
string email = cookie["Email"];
both provider and email are null. How can I get values from cookie?
EDIT
Cookie is saved with:
HttpCookie cookie = new HttpCookie("Login");
cookie["Provider"] = "Custom";
cookie["Email"] = "test#gmail.com";
Response.Cookies.Add(cookie);
SECOND EDIT
I think the problem is encryption. I am using my own encrpytion mechanism. Cookie.value looks fine after decryption, but Cookie.Values is a little bit different than original. I think that's the problem.
Cookie.Value (before encryption): Provider=Custom&Email=test#gmail.com
Cookie.Value (after decryption): Provider=Custom&Email=test#gmail.com
Cookie.Values (before encryption) :{Provider=Custom&Email=test%40gmail.com}
Cookie.Value (after decryption - is different): {Provider%3dCustom%26Email%3dtest%40gmail.com}
Try below
HttpCookie cookie1 = Request.Cookies["Login"];
if (cookie1 != null)
{
string provider = cookie1["Provider"].ToString();
string email = cookie1["Email"].ToString();
}

Response cookie not updating

When I log I create the following cookie:
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
When I request data from this cookie, I use Request.Cookies:
string username = Convert.ToString(Request.Cookies["Ortund"]["Username"]);
When i log out, I do this:
HttpCookie cookie = new HttpCookie("Ortund");
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.Cookies.Add(cookie);
For some reason, now I'm sitting with a cookie that has an expiry date of 0001-01-01 12:00:00 AM in Request.Cookies["Ortund"] and the expiry date of the cookie doesn't change no matter how many times I log in.
Have I done something wrong here? Is this even close to how it should be done?
In your logout you are creating a new instance of the cookie. Also you are using Response.Cookies.Add which may allow multiple cookies of the same name to be appended to the Response.
I would suggest you to check the Request for the cookie key and if it doesn't exist add the cookie.
For updating the cookie, first get the existing cookie object and use Response.SetCookie to update the value.
Code
set
if(!Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
}
update
if (Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = Request.Cookies["Ortund"];
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.SetCookie(cookie);
}

Making server cookies secure

I've been trying to figure out how to set the secure flag on all the server cookies for our website. We're running .NET 4.5. I tried adding <httpCookies requireSSL="true" /> to the web.config file. I tried adding <authentication><forms requireSSL="true" /></authentication>. I tried setting the secure flag in code. Nothing had any effect. Adding the following c# function to Global.asax.cs was supposed to work, but didn't:
protected void Application_EndRequest()
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
if (sCookie.Equals(authCookie))
{
// Set the cookie to be secure. Browsers will send the cookie
// only to pages requested with https
var httpCookie = Response.Cookies[sCookie];
if (httpCookie != null) httpCookie.Secure = true;
}
}
It finally started working after I got rid of the "if (sCookie.Equals(authCookie))..." statement. So this is the working version:
protected void Application_EndRequest()
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
// Set the cookie to be secure. Browsers will send the cookie
// only to pages requested with https
var httpCookie = Response.Cookies[sCookie];
if (httpCookie != null) httpCookie.Secure = true;
}
}
I have several questions. First, what is the logic behind putting this in the Application_EndRequest method? Second, why did I have to get rid of the sCookie.Equals(authCookie)) part? Finally, has anyone found a more elegant solution? Thanks.
If you are executing the request over HTTP and not HTTPS then I do not think you can set Secure = true. Can you verify that you are running over a secure connection? You can do some google / bing searches on how to generate a local certificate if you are testing on your dev box. Also do not forget to encrypt your cookie so its not readable on the client side.
Here is some sample code.
var userName = "userName";
var expiration = DateTime.Now.AddHours(3);
var rememberMe = true;
var ticketValueAsString = generateAdditionalTicketInfo(); // get additional data to include in the ticket
var ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expiration, rememberMe, ticketValueAsString);
var encryptedTicket = FormsAuthentication.Encrypt(ticket); // encrypt the ticket
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = true,
};
EDIT - Added link
Also take a look at this previous answer and how you can configure your web.config to ensure that cookies are always marked as secure.

redirection between asp .net interfaces using cookies without querystring

I have two asp .net interfaces:
1. app1.domain.com
2. app2.domain.com
In default page of both, there is a link button from which we can switch between them. Previously we use query strings to pass username and password. But now we want to use cookies.
So in click event of link button, I have code like this:
HttpCookie cookie = new HttpCookie("MYCookie", Guid.NewGuid().ToString());
cookie.Domain = "domain.com";
cookie.Expires = DateTime.UtcNow.AddHours(1);
cookie.HttpOnly = false;
cookie.Secure = true;
cookie.Values.Add("Username", Username.ToString());
cookie.Values.Add("UserId", UserId.ToString());
Response.Cookies.Add(cookie);
Response.Redirect(destinationAddress);
Now, in default page of other application am reading cookie as:
protected override void InitializeCulture() {
if (Request.Cookies["MYCookie"] != null) {
HttpCookie cookie = null;
cookie = Request.Cookies.Get("MYCookie");
}
}
but here am finding Request.Cookies["MYCookie"] as null. Am i missing anything? Please advice.
It looks to me like the problem is your domain.
Change cookie.Domain = "domain"; to be cookie.Domain = ".domain.com";
I think you need to add HttpCookie same Path property for both app1 and app2
Response.Redirect generates ThreadAbortException.
All the changes made in your cookie will be lost. so you can use,
<meta http-equiv="Refresh" content="10; URL=your url" />
c# code:
System.Web.UI.HtmlControls.HtmlMeta meta = new System.Web.UI.HtmlControls.HtmlMeta();
meta.HttpEquiv = "Refresh";
meta.Content = "10; URL=your url";
Page.Header.Controls.Add(meta);
And set you cookie as like
cookie.Domain = ".domain.com";

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