Problem with HttpOnly Cookies - c#

I have a problem with creating HttpOnly Cookies , I use the following code to creat new cookie:
//A.aspx
HttpCookie ht = new HttpCookie("www");
ht.Value = "www";
ht.Name = "www";
ht.HttpOnly = true;
ht.Expires = DateTime.Now.AddDays(1);
Response.AppendCookie(ht);
Response.Redirect("B.aspx");
//B.aspx
HttpCookie cookie = Request.Cookies["Allowed"];
HttpCookie htt = Request.Cookies["www"];
if (cookie != null)
{
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
else
{
cookie = new HttpCookie("Allowed");
cookie.HttpOnly = true;
cookie.Value = "ping";
cookie.Expires = DateTime.Now.AddMinutes(2);
Response.Cookies.Add(cookie);
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
The problem is that the final result is always : False, although the HttpOnly property is set to True .
Can anyone explain me a way to figure this out ?
Thanx

Cookie parameters (expiration date, path, HttpOnly etc) are not sent back to the server by the browser, only the values. Sending them back would only introduce unnecessary bloat. Therefore the cookies in Request.Cookies will only contain the names and values.
If you want to see if your HttpOnly value is taking effect, use Firecookie or something similar to inspect the cookies. Or try accessing them in JavaScript - that's what it's supposed to prevent.

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.

cant get cookie Values (NameValueCollection) - ASP.NET MVC

I used belowe code to add cookie , I add some key, value in cookie ,
public static void AddCookie(this HttpContextBase httpContextBase, string cookieName, NameValueCollection cookieValues, DateTime expires, bool httpOnly = false)
{
var cookie = new HttpCookie(cookieName)
{
Expires = expires,
//Value = httpContextBase.Server.UrlEncode(value),// For Cookies and Unicode characters
HttpOnly = httpOnly
};
cookie.Values.Add(cookieValues);
//httpContextBase.Response.Cookies.Add(cookie);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
and fill keys like this :
NameValueCollection CookieValues = new NameValueCollection();
CookieValues.Add("pid", shoppingCartViewModel.ProductId.ToString());
CookieValues.Add("qty", "1");
HttpContext.AddCookie(shoppingCartCookiName, CookieValues, DateTime.Now.AddDays(1));
when I want read cookie , Values are null .
I used belowe code to check Cookie Value
public static NameValueCollection GetCookieValues(this HttpContextBase httpContext, string cookieName)
{
var cookie = System.Web.HttpContext.Current.Response.Cookies[cookieName];
if (cookie == null)
return null; //cookie doesn't exist
// For Cookies and Unicode characters
return cookie.Values;
}
You need to use Request.Cookies not Response.Cookies while reading the cookie.
Instead of
System.Web.HttpContext.Current.Response.Cookies[cookieName]
Use
System.Web.HttpContext.Current.Request.Cookies[cookieName]
In a web application the request is what comes from the browser and the response is what the server sends back. While reading cookie data from the browser you should use the Request.Cookies. When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.
Use this.
HttpCookie cookie = HttpContext.Request.Cookies.Get("name");

C# persistent cookie

I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow.
But I can't figure out why the code below isn't working.
First I write to the cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
I see the cookies stored in Internet Explorer. The content looks OK.
Then the reading code:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.
I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?
try with below code :-
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
Non-Persist Cookie - A cookie has expired time Which is called as
Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the
Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request
object. Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;
Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.

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.

Delete cookie bug in IE?

I'm trying to delete some cookie which was set by javascript, it works well in Firefox and Chrome but not in IE, it deletes the cookie value in IE but not the file, so when I'm loading the page which uses cookie it loads some junk instead of nothing after delete.
I set the cookie like this
var exdate = new Date();
exdate.setDate(exdate.getDate() + 1);
var c_value = escape(data.d) + "; expires=" + exdate.toUTCString();
document.cookie = "user" + "=" + data.d;
and delete it like this
document.cookie = 'user=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
where is my problem?
I also have the code in C# for ASP.Net to delete the cookie, but it doesn't work in none of web browsers, (it works for cookie which was set by C# but not with Javascript) where is the problem with this code as well?
FormsAuthentication.SignOut();
Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);
Session.Clear();
Response.Cookies.Clear();
you must send cookie to the response stream otherwise your modification will never be committed to the browser.
I usually use this code to logout:
FormsAuthentication.SignOut();
CurrentContext.Session.Abandon();
HttpCookie c = CurrentContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
CurrentContext.Response.Cookies.Add(c);
}
While creating cookie Try to include domain name
Response.Cookies("abc").Domain = ".xyz.com"
and while deleting
Response.Cookies("uid").Value = Nothing
Response.Cookies("abc").Expires DateTime.Now.AddDays(-1)
Response.Cookies("abc").Domain = ".xyz.com"
and Check your cookies using below Tools
http://www.nirsoft.net/utils/iecookies.html

Categories