Thursday, March 26, 2015

Cross Site Scripting Attack Prevention

Last week I discussed what cross site scripting attack is. In today's blog post I am going to discuss some measures which can help prevent cross site scripting attack in MVC applications.

How to Prevent

Encoding the content is the best way to prevent XSS attack. We need to encode both HTML and Javascript content. Let's discuss each of these one by one.

Encode HTML

The output on the pages should be HTML encoded or HTML attribute encoded. In Web Forms, we could use Html.Encode like this:

<% Html.Encode(Model.DataToEncode) %>

 Or shorthand like this:

<%: Model.DataToEncode %>

The Razor View Engine HTML encodes output by default. So a Model property on the View like this:


will be automatically encoded.
If we want to access raw data with no encoding then we need to use Html.Raw like this:


One should be extremely careful while using Html.Raw() as it opens doors for many security vulnerabilities.

Encode Javascript

Similarly, if we need to display user input in Javascript, we should do Javascript encoding like this:


In the example, that I gave in my previous blog post, if the attacker tries to provide malicious input like this:

 and the input is Javascript encoded then it will be rendered like this:

XSS Prevention


In order to prevent cross site scripting attack, we should not trust user input. We should always HTML encode/ Javascript encode the data.
For future updates to my weekly blog, please subscribe to the blog and follow me on Twitter. Until then Happy Coding :)

"Professional ASP.NET MVC 5"