ARTICLE

Avoiding Cross-Site Scripting (XSS) Attacks With AntiXSS in MVC 4

Posted by Abhimanyu K Vatsa Articles | ASP.NET MVC March 15, 2013
In this article you will learn, with examples, how to avoid XSS attacks in MVC Applications with Microsoft's AntiXSS library.
Reader Level:

In this article you will learn how to avoid XSS attacks in MVC Applications with Microsoft's AntiXSS library. I will show you a case where a user submits malicious HTML markup with a message and it starts displaying an annoying alert. Then I will move on and show you how to prevent it with AntiXSS.


In my application my intent is to allow the user to enter HTML markup with a message. In MVC, when you try to submit HTML markup it will show you an error.

 

See, what I'm trying to create is something as in the following:
 

MVC1.jpg

 

But because of HTML markup in the message MVC rejected my request saying A potentially dangerous Request.Form value was detected from the client (MessageText="Hello <b>Admin</b> I am Ab...").

 

MVC2.jpg

 

By default, MVC rejects such requests containing HTML markup to prevent Cross-Site Scripting attacks and this is one advantage of MVC since if you forgot to work on XSS preventions then you still win.

 

If you want to allow the user to submit HTML markup with a message then you can allow it in one of the following ways.

 

1st Way (Model Level):-

 

MVC3.jpg


2nd Way (Controller Level):-

 

MVC4.jpg

Use any approach given above, this will skip the request validation. But there is still a problem, by default Razor will encode the HTML markup.

 

MVC5.jpg

 

To fix it, for this we can use @Html.Raw(item.MessageText).
 

MVC6.jpg

 

So, I have allowed writing HTML markup with MessageText, but see how now a user is trying to send a malicious script with the message text.

 

MVC7.jpg

 

MVC8.jpg

 

So, whenever you allow HTML markup to be written you must be extremely careful with its prevention. So, here the Microsoft library AntiXSS is useful, let's use this library.

 

Open NuGet and search for the "AntiXSS" package and install it.

 

MVC9.jpg

 

You will find two new dlls AntiXssLibrary and HtmlSantizationLibrary in your project references folder.
 

MVC10.jpg

 

Now, just one change in the controller will enable XSS prevention.

 

MVC11.jpg

 

And when any user tries to send a malicious script with a message this will automatically be dropped from the string.

 

MVC12.jpg

 

So, in this article you learned how to prevent XSS attacks with the AntiXSS library.

 

COMMENT USING
Employers - Post Free Jobs