Breeze and empty string (server side) - breeze

Is there a way to make breeze api on server treat empty strings as null?
This is default behaviour for binding models in ASP. Now it's broken with the usage of BreezeController and EFContextProvider.
UPDATE:
I'm using breezejs with knokout. The error ocurred with email field: this field is not required, but empty string is validated by .NET EmailAddressAttribute.
The situation: user changes settings that has this email field. If field is not changed it remains null, but when it has been changed and cleared then on saving server throws validation error for this field.
ApiController would have binded entity and cleared empty strings for me, but BreezeController does not do this. Now I have to manually clear empty strings in EFContextProvider.BeforeSaveEntity.

Related

Readable data in querystring on HTTP Get

We've had a penetration test on a website and they're saying we shouldn't be passing readable data in a querystring (it's an Email Address).
The querystring is being created by the application when ModelState.isValid fails and it returns the model to the view with a HTTP GET. We are being told the EmailAddress value should be encrypted (the site is SSL).
The penetration result :
GET /Membership/RegisterMe?__RequestVerificationToken=26Oajd6AG17YkHhyZz8-pArBuKEEer7V0b86f0aR_jHXs2JqYRE8NHvhz1zCcKWtQ6eVtxtdkTvC6HjG1ami2d-2CPn8Ieedwc77fIoMB941&EmailAddress=SomeOnesEmail.com
We tried to convert the value after it's submitted by doing the following in the controller, so if validation fails it will returns an encrypted value in the querystring:-
ModelState.Remove("EmailAddress");
model.EmailAddress = Helpers.Encryption.Encrypt(model.EmailAddress);
But it loses the validation messages on the property, for example if it's an invalid email address.
Turns out using HTML Helpers in your View makes it difficult to change Model values on Postback (validation fail). It will always return the original values from the HTML helpers in the form. You can change it like so:-
ModelState.Remove("EmailAddress");
Model.EmailAddress = //new value;
My problem was I needed to keep the EmailAddress value but encrypt it before Postback, so the value is not exposed in the querystring. The above was no good as using ModelState.Remove, you also lose the Validation message (invalid Email Address etc.).
Reason was because of the HTML Helpers in the form - #Html.TextBoxFor. Changed this to
<input type="text" name="EmailAddress">
You can then change the value in the controller before postback and maintain the validation errors
Model.EmailAddress = Encrypt(Model.EmailAddress);
The postback value is encrypted and the appropriate validation error messages are displayed to the user in the View. Then did some simple code in the View to decrypt the Model.EmailAddress.

Why is there a difference in the validateantiforgerytoken cookie value and hidden form value?

I have got the MVC4 [ValidateAntiForgeryToken] attribute working perfectly. However, I don't understand what I am seeing in Fiddler. The cookie sent by the server to the browser is set to this value:
__RequestVerificationToken=FVcmfj07ZEuBdjGuqWu14KIzolxr0ArLgvbNdnq0c4DFywxSA31yIHbm2IzgTPMVhMl4STEh2re8oGmwsSjKtSBTolCsmyGGRnLE1qurUqA1
but the hidden form input is set to this value:
OxjO3NjS1ly-bqP9RnYK9Vx8ZJyLGVCuTQEuSCAQWofVmuJaRkEcnHAHWcDurXaH6DhUiZ6XY5wCgi70u19mPy9sydMrkuS9qlWMXxGL_401
i.e. they appear different where they should match. Am I not understanding cookies properly and perhaps the first string is not the actual 'value' of the cookie encrypted?
Source Pro ASP.NET MVC 3 Framework:
The __RequestVaerificationToken hidden field contains a random component (matching the one in the cookie), but that's not all. If the user is logged in, then the hidden field value will also contain their user name (obtained from HttpContext.User.Identity.Name and then encrypted).
[ValidateAntiForgeryToken] checks that this matches the logged-in user. This adds protection in the unlikely scenario where an attacker can somehow write (but not read) cookies on your domain to a victim's browser and tries to reuse a token generated for a different user.

MVC Side effect of using [HttpPost, ValidateInput(false)]

I have a TextArea in my strongly typed View defined with
#Html.TextAreaFor(x => x.Text)
My controller Action originally looked similar to this:
[HttpPost]
public ViewResult Index(MyViewModel vm)
{
using (var db = new MyEntities())
{
Post p = new Post();
p.Text = vm.Text;
db.Posts.AddObject(p);
db.SaveChanges();
}
return View();
}
This worked fine. The text the user entered into the TextArea was passed into the controller and saved into the Post table in SQL Server via Entity Framework. The data type for this field is varchar(1000). (There is also Model validation on the Text field using MetadataType with [StringLength(1000)] validation.)
I noticed that if I tried to copy some HTML source and paste it into the TextArea and submit it, I received the following error:
"A potentially dangerous Request.Form value was detected from the client"
The error led me to this question, and the take away from there was that I could simply add
[HttpPost, ValidateInput(false)]
to my Action to stop that type of validation. This worked wonderfully, but to my surpise, no matter what I tried putting into the TextArea, I couldn't cause any problems. If I paste in javascript, html or T-SQL statements riddled with quote characters, it still works fine. I see the exact characters I entered into the TextArea appearing in the SQL table, and if I display the text back to the View, I see in the source each character is converted to the HTML counterpart, and the display on the screen looks just like it did when I entered it in. I did not do any sort of text conversion to accomplish this. It seems by default everything is working exactly as I want it to. Of course I'm glad for this, but when I read about disabling the validation, it is often followed with a warning that you should understand the consequences of doing this, and I don't think I do. So I wonder, what are the consequences? Is there anything someone could possibly type into my TextArea that could mess things up as a result of disabling the input validation?
In case it's relevant, my particular setup is MVC4, .NET 4.0, Entity Framework 4.4, SQL Server 2012 Express.
If you are using razor any text that you output will automatically be encoded which will appear as text in the browser but not be interpreted as javascript etc.
If you are turning validation off you have to be very careful to ensure that you are encoding all user input whereever you display it so that you dont inadvertently run some javascript on your page due to somethign a user entered (look at XSS for some examples).
You can test quickly (althought not an exhaustive search) by adding some kind of javascript alert('hello') call to various varchar fields in your database and see if it gets called when you visit the page.
Also even if you arent displaying the user data it may have implications depending on how you do your data access.
Even if you use something like entity framework you are not protected from sql injection for instance if you used stored procedures and did not do validation checking on the input. See Troy Hunt's article on this

How to persist JSF view parameters through validation

I am using JSF 2.0/CDI and PrimeFaces 2.2.1 for a number of CRUD forms that let the user view or update the attributes of an existing entity by clicking on a link in a datatable, where the identifier of the entity is passed to the CRUD form as a View Parameter. I display the entity's ID (often just an integer) on the CRUD form in a PrimeFaces InputText field with the readonly attribute set to true (since I can't let them change it), so the user knows which entity they're editing. The backing bean of the CRUD form is RequestScoped, which works fine except when validation fails. In that case, the value of the View Parameter is lost, so a 0 is displayed in the entity ID field on validation failure.
I am able to maintain the actual entity ID in a hidden field so it's available to update the database once validation succeeds, but it's rather maddening that I've not been able to find a way to maintain the value in a visible field of some sort after a validation failure. Ideally the InputText field would retain its functionality as an inputted and validated field even with its readonly (or disabled) attribute set to true, which would let me forgo the hidden field entirely. But it doesn't appear that I can make it work that way. Any suggestions besides making the backing bean ConversationScoped, which I'd prefer to avoid?
Actually, after stating what I'm looking for a little differently in a Google search I found a novel suggestion at the link below that seems to work cleanly. Instead of making the entity ID field readonly or disabled, I leave it enabled but blur it as soon as it receives focus. I'm able to get rid of the hidden field, the user can't change the value and it survives a validation failure.
<p:inputText id="entid" value="#{RequestBean.entityID}" onfocus="blur();" />
http://www.codingforums.com/archive/index.php/t-1738.html

MVC Validation Error Messages not hardcoded in Attributes

I have a requirement that the validation error messages that are passed to my view come from the database.
I want to use data annotation on my model but the error message key in validation attributes can only be a string or a constant.
I'm open to other solutions for validation but I need to pull the error messages from the database.
Are there any other ellegent solutions for validation were the error message is not a string? Right now I am thinking about using T4 to generate a constants file...
My specific problem can be solved by using the ASP.NET MVC2 Metadata and Model Validation Providers.
Here are the articles that got me started:
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
http://dotnetslackers.com/articles/aspnet/customizing-asp-net-mvc-2-metadata-and-validation.aspx
http://haacked.com/archive/2009/10/01/asp.net-mvc-preview-2-released.aspx
You could overload the validation runner to swap out error messages with ones from a database.

Resources