Wednesday, January 09, 2008

Be careful outputting strings in ASP.NET MVC

During my presentation at Alamo Coders last night, someon mentioned that it is unsafe to output user-entered strings like this:

<h2><%= college.Name %></h2>

The reason is, of course, that the user could be malicious and enter in a string such as this:

“<script>alert(‘I am evil’);</script>”

And it would evaluated on the page and all of your users would get an alert box.  This is leaving your door wide-open to clever attacks known as Cross Site Scripting and is very dangerous.

Instead, we should escape these strings so that they aren’t rendered as HTML or javascript, but rather textual characters.  That means that < will be translated to &lt; and so on.

To do that, the Html helpers that ship with the framework give you an Encode method, letting you do something like:

<h2><%= Html.Encode(college.Name) %></h2>

But the syntax is a bit cumbersome for every outputted value on a page.  I prefer the way Rails handles it… like this:

<h2><%= h(college.Name) %></h2>

And it turns out that you can add this extension method somewhere and be done with it:

public static string h(this ViewPage page, string input)
{
     return new HtmlHelper(page.ViewContext).Encode(input);
}
And that’s it!  Just remember to take this precaution, or you’ll regret it later.
Personal Loans - Loans - Debt Consolidation - Unsecured Loans