ValidateInput(false) vs AllowHtml

EricGS picture EricGS · Sep 2, 2014 · Viewed 49.4k times · Source

I have a form that is used to create a memo, to do that I am using a rich text editor to provide some styling, this creates html tags in order to apply style. When I post that text, the mvc throws an error to prevent potentially dangerous scripts, so I have to specifically allow it.

I have found 2 ways of doing this, one is to decorate the controller method with [ValidateInput(false)] and the other is to decorate the ViewModel attribute with [AllowHtml]. To me, [AllowHtml] looks much nicer, but I have only found that approach used 1 time and the [ValidateInput(false)] seems to be the preferred way.

Which method should I use and what are the differences between the two?

Answer

Shivprasad Koirala picture Shivprasad Koirala · May 29, 2015

ValidateInput and AllowHTML are directly connected with XSS security issues.

So let us first try to understand XSS.

XSS (cross-site scripting) is a security attack where the attacker injects malicious code while doing data entry. Now the good news is that XSS is by default prevented in MVC. So if any one tries to post JavaScript or HTML code he lands with the below error.

Enter image description here

But in real time there are scenarios where HTML has to be allowed, like HTML editors. So for those kind of scenarios you can decorate your action with the below attribute.

[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
    return View(obj);
}

But wait, there is a problem here. The problem is we have allowed HTML on the complete action which can be dangerous. So if we can have more granular control on the field or property level that would really create a neat, tidy and professional solution.

That’s where AllowHTML is useful. You can see in the below code I have decorated “AllowHTML” on the product class property level.

public class Product
{
    public string ProductName { get; set; }
    [AllowHtml]
    public string ProductDescription { get; set; }
}

So summarizing “ValidateInput” allows scripts and HTML to be posted on action level while “AllowHTML” is on a more granular level.

I would recommend to use “AllowHTML” more until you are very sure that the whole action needs to be naked.

I would recommend you to read the blog post Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML which demonstrates step by step about the importance of these two attributes with an example.