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

In this article you will learn how to avoid XSS attacks in MVC Application with Microsoft’s AntiXSS library. I will show you a case where user will submit the malicious HTML markup with message and it will start displaying annoying alert. Then I will move on and show you how to prevent it with AntiXSS.

In my application I’m wishing to allow the user to enter HTML markups with message. In MVC, when you try to submit HTML markups it will show you error.

See, what I’m trying to create.

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...").

By, default MVC rejects such requests containing HTML markups to prevent Cross-Site Scripting attacks and this is one advantage of MVC because in case you forgot to work on XSS preventions, you still win.

In case if you want user to submit HTML markups with message, you can allow it in following ways.

1st Way (Model Level):-

2nd Way (Controller Level):-

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

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

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

So, whenever you allowing to write HTML markups you have to be extremely careful with its prevention. So, here Microsoft library AntiXSS comes in action, let’s use this library.

Open NuGet and search for ‘AntiXSS’ package and install it.

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

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

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

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

Hope this helps.


Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples