MVC Cookie losing values after a HTTP Request & Cookie Add value - asp.net

I have a multi key-value pair cookie. The cookie is a session cookie, i.e. not persistent. It contains several key-value pairs of data and well within the 4k size limit.
What's working: In my initialise action method (on Controller A), the cookie has a number of key-value pairs successfully added to it. All good so far.
Problem: When I navigate to another page, i.e. different action method (on Controller B), and then add a value to the cookie, I find all the previous values in the Cookie are now gone.
Please note, I verified the problem occurs only when a new value is added here. NOT adding a value to the cookie and navigating across many pages (and controllers) the existing values in the cookie are all preserved.
Investigations: I have spent one and a half days on this and tried a number of thing. In my cookie WriteCookie() method:
Making the Cookie persistent (by setting it's expiry to tomorrow). Verified the cookie in Firefox exists and has the correct date. But once I add a value to the cookie in Controller B, the cookie has lost all it's data.
Create a new cookie with the same name, added the previous values to this new cookie along with the new value. But again, navigating to another page (Controller B) and adding a value to the cookie has lost all it's previous data.
Code: Below is the original code I started with which doesn't contain the many heartbreaking attempts:
public static class CookieHelper
{
public static string ReadCookie(string key)
{
string value = string.Empty;
HttpCookie cookie = HttpContext.Current.Request.Cookies["mycookie"];
if (cookie != null)
{
value = HttpContext.Current.Request.Cookies["mycookie"].Values[key];
}
return value;
}
public static void WriteCookie(string key, string value)
{
HttpContext.Current.Response.Cookies["mycookie"].Values[key] = value;
}
}
Can anyone please help and explain why the cookie values are being lost. My guess, for some unknown reason subsequent writes to the cookie AFTER a HTTP Request is creating a new cookie and overwriting the existing cookie.

From MSDN:
You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.
Modifying an individual subkey is the same as creating it.
To delete an individual subkey, you manipulate the cookie's Values collection, which holds the subkeys. You first recreate the cookie by getting it from the Cookies object. You can then call the Remove method of the Values collection, passing to the Remove method the name of the subkey to delete. You then add the cookie to the Cookies collection so it will be sent in its modified form back to the browser.

Related

Why does HttpContext.Response.Cookies["foo"] add a cookie?

I have just spent half a day tracking down a bug due to the following behaviour: -
Imagine that there is not a cookie called "foo" in either the Http request's or response's cookie collections. The following code returns null
A) HttpContext.Current.Request.Cookies["foo"]
The following code creates a new cookie called "foo" (with path="/" and blank value), adds it to the response's cookie collection and returns that
B) HttpContext.Current.Response.Cookies["foo"]
So (B) has the side effect that any pre-existing cookie called "foo" is overwritten on the client's browser.
This is not a bug. Someone actually coded this deliberately. Here is the disassembly of the Get method (the Item[string name] indexer delegates to this method.
public HttpCookie Get(String name) {
HttpCookie cookie = (HttpCookie)BaseGet(name);
if (cookie == null && _response != null) {
// response cookies are created on demand
cookie = new HttpCookie(name);
AddCookie(cookie, true);
_response.OnCookieAdd(cookie);
}
return cookie;
}
Obviously the MSDN docs do not mention this behaviour (although some users have added comments at the bottom of the docs that describe this behaviour).
My question is can someone explain to me the rational why the HttpCookieCollection class has this behaviour.
From MSDN doc about HttpCookieCollection.Get method: http://msdn.microsoft.com/en-us/library/ezy11xy2.aspx
If the named cookie does not exist, this method creates a new cookie
with that name.
So yes, this is done on purpose.
Why? At a guess because it makes sense. If you're doing anything with the response the typical use case is that you want things to be sent to the browser.
You check for values inbound (Request.Cookies) and then you set them outbound (Response.Cookies). The Request is a READ, the Response is a WRITE.

ASP.NET session key for web service security?

I've got a web service (ASP.NET 2.0) that I'm calling from javascript using jQuery's $.ajax(). I've been told that the session key is often used as a nonce in a situation like this for security purposes; the web service takes a key as one of its parameters and only returns data if it matches the current session key.
I'm attempting to accomplish this by setting the value of a hidden field to the current SessionID on every Page_Load (i.e. every postback), then grabbing it in the javascript to pass as a parameter. But it's never the same key as the web service's current key (Context.Session.SessionID).
Is this possible to resolve, or should I be doing this another way?
EDIT: code to set session in hidden field as requested.
hfSession.Value = Context.Session.SessionID;
That's in the Page_Load of a .ascx control, not under any conditional (i.e. not wrapped with if (!Page.IsPostBack).
I believe you are trying to prevent Cross Site Script Request Forgery (CSRF). The Session ID is actually sent across as a cookie and the attacker can set this. Rather than use the Session ID itself, you should use a randomly generated number stored in a Session variable.
String GetCSRFToken()
{
String token = (String)Session["CSRFToken"];
if( token == null )
{
token = GenerateLongRandomString();
Session["CSRFToken"] = token;
}
return token;
}
void AssertValidCSRFToken(String token)
{
if( token != GetCSRFToken() )
{
throw new Exception("Invalid Request!")
}
}
Here is a link to another question with more info on preventing this kind of attack:
CSRF Validation Token: session id safe?
Asp.net actually generates a new Session ID for every request until you use the Session State to store some value. This could be a reason why the values are different. Try and save something in the session. Perhaps
Session["SessionID"] = Context.Session.SessionID;
hfSession.Value = Context.Session.SessionID;
A new SessionID is generated each time the page loads until the session is actually allocated. So if you don't actually allocate anything to the session, the SessionID will change upon each page load.

Preventing Re-submission of data on Browser Refresh

I have a form. On submit of a button, it inserts a record into the db. If I go back in my browser and refresh the page it's resubmitting it causing all sorts of issues as you can imagine. How do I ensure that the user can't refresh the previous page and the state of that page does another automatic submit on refresh like this?
I'm not using ViewState. I actually have it disabled in the page directive
No, Response.Redirect does NOT solve this problem. The user can still go back with the browser's back button and refresh at the point where they submitted and it will still run the button's event sending the data downstream to my DL insert
The solution I use most often is this:
When the user first visits the page (Non-PostBack), generate a token value (GUID is easy). Take this token value and store it in their Session variables and a hidden field in the page. Being a field, this value should persist through round trips to the server without ViewState enabled (I could be mistaken on that count, so please check it!). Should the page be refreshed (and form values lost), a new value will be generated by the Non-PostBack initialization.
When the page is posted back, retrieve the hidden field value and compare it against the expected value in the user's Session variables:
If the tokens match, accept the submission as "genuine", remove the token from the Session variables, and continue your workflow.
If the token is missing from Session variables, the user is trying to submit the form again. - If the tokens do not match, the user is "replaying" an old submission of the form.
Example code to achieve this sort of solution:
public partial class MyPage : Page
{
protected HiddenField tokenField;
protected void Page_Load()
{
if(!IsPostBack)
CreateToken();
}
// Call this method to establish a token in session and on the page.
private void CreateToken()
{
string token = new Guid().ToString();
Session["dupeToken"] = token;
tokenField.Value = token;
}
// Call this method to validate the token before continuing workflow.
private bool TokenIsValid()
{
string expectedToken = (string)Session["dupeToken"];
if(expectedToken == null)
return false;
string actualToken = tokenField.Value;
return expectedToken == actualToken;
}
// Call this method when the page submission is complete to prevent re-submission.
private void ConsumeToken()
{
Session["dupeToken"] = null;
}
}
The easiest way would be to wrap the form in an < asp:UpdatePanel>. That way, all postbacks are done via AJAX and the browser will never ask you to re-submit your form.
The best two ways of doing this are:
Performing a check on a distinct field against the database
Create a hidden token in the form that uses a salt based on time. If you put logic in script to check for the existing time and compare it to the token, you can either allow the submission or define it. For example, if the form is drawn at a certain time, you store the token, and within 30-60 seconds you can submit, but after that you cannot.

ASP.NET: How to redirect, prefilling form data?

i want a handler to redirect to a web-forms page, pre-filling in the values of some controls on the form.
i tried setting my current Request.Form data:
if (theyWantToDoSomething)
{
//pre-fill form values
context.Request.Form["TextBox1"] = "test";
context.Request.Form["ComboBox1"] = "test 2";
context.Request.Form["TextBox2"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return;
}
But i get an exception that Form values are read only.
What would be a way to send the client to another page, pre-filling form data?
Answer
i used the Session state to store values. It's important to note that by default a Handler doesn't have access to Session (the Session object will be null). You have to tell IIS to give you the Session object by adding the IRequiresSessionState marker interface to your handler class:
public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
...
if (theyWantToDoSomething)
{
//pre-fill form values
context.Session["thing1"] = "test";
context.Session["thing2"] = "test 2";
context.Session["thing3"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return; //not strictly needed, since Redirect ends processing
}
...
}
}
You can only populate your Response, the Request is input data and is indeed read-only.
If you are using ASP.NET, there are a variety of ways you could accomplish what you need:
The best way would probably be to pass the data you need to be pre-populated to SomeWebForm.aspx via the Session object, and on that pages Load method, populate your form. Keep in mind that when you do Response.Redirect, a 302 response is sent to the client with the URL the client should redirect to. The process is transparent to the user...but there is a full round trip involved.
Another alternative to populating the users Session would be to add GET parameters via a query string to the redirect to SomeWebForm.aspx.
If you need to transfer processing to the SomeWebForm.aspx page without round tripping, you could use Server.Transfer. This will transfer execution from the current page to the page you choose...however, this can cause some odd behavior on the client end because the URL does not update. As far as the user is concerned, it will still appear as though they are on the same page they started on.
A few ideas that might get you started:
Pass the values in the query string
Store the values in the session state or in a seperate cookie
Store the values in HttpContext.Items and use Server.Transfer instead of Response.Redirect
Another approach that hasn't been mentioned yet is using Server.Transfer makes it possible to use the Page.PreviousPage property, allowing access to the controls on the page that transferred control.
As jrista mentioned though, using Transfer doesn't update the URL shown to the user, which may or may not be an issue. For example, a user can't precisely bookmark a page they got transferred to since the URL will be that of the original transferring page.

.net cookies, do I have to send to browser?

After I create or modify a httpcookie, do I have to do add it to the response.cookies collection? (if yes, only if its a new cookie or even if I am modifying one)
If you don't add a cookie to the Response.Cookies collection, it will never be sent to the browser. However, once you add the cookie to the collection, you can modify it as you please and the last value you set is what will be sent to the browser. What you are adding to the collection is a reference to your HttpCookie object, and the cookie is not sent to the browser until the end of the request life cycle.
If it is new it needs to be added to the Response.Cookies collection to be stored, but you can access the collection like an array.
Response.Cookies["foo"] = myCookie;
This will take care of the adding for you. FYI, if the cookies has not been created the value will return null.
However the cookie will be updated if you refer to the collection like this:
HttpCookie myCookie = Response.Cookies["foo"];
Any modifications to myCookie will be made to the cookie in the collection because in C# when you assign a variable to an existing class object, that object is handled by reference and it is modified.

Resources