0

I've a Web API project which is consumed by an MVC project. The MVC project has a fair amount of user inputs which are displayed as output on the web page.

Now, I want to protect my site from XSS attacks. I've read about Microsoft's AntiXss library, input validations, output filtering etc. But my question is, How do I apply this to my project. Where to put input validations, how to filter my output, how do i sanitize user data, do I need to sanitize the data in APIs also or just in MVC before I send it to the APIs, and if yes, then how, where to use AntiXss library, in MVC or in web API, and how etc.

Gabor Lengyel
  • 14,129
  • 4
  • 32
  • 59
NoviceCoder
  • 31
  • 2
  • 8

1 Answers1

1

The answer depends on how exactly user input makes its way into the page DOM in the browser.

If the MVC application generates cshtml pages (with Razor), you need to implement output encoding there, in cshtml files. Note that AntiXSS as a separate library is now deprecated, it's now in the System.Web.Security.AntiXss namespace by default. You need to encode all output according to the context that they get written into (most importantly, you need to encode any input that's written in a Javascript context, be it a script tag, an event attribute like onclick, the first character of a href for an a tag, etc). For plain html output (text between tags) Razor already provides html encoding by default, so it's ok to just do <div>@myVar</div>.

If your frontend consumes something like a JSON API, then you probably have some kind of a client side template engine (Knockout, etc). In that case, it's reasonably safe to send data as received from the user back to the client with an application/json content type (that's actually very important). Then you have to carefully select binding methods to always bind user input as text and not as html to the page elements. This practically means things like using Knockout's text binding instead of html or using jQuery's .text() method instead of .html(), etc.

Please note that a full tutorial on XSS prevention would be way longer than an answer here, so this answer only highlights some high level things and the general way this should be done to prevent XSS.

Gabor Lengyel
  • 14,129
  • 4
  • 32
  • 59
  • and no need to do anything on the API side? – NoviceCoder Nov 01 '16 at 04:46
  • Not for XSS prevention. You should not encode data before saving it, or when serving from the API, because the API has nothing to do with how to present your data (which encoding to choose). See my answer to [this question](http://stackoverflow.com/questions/39778598/sql-preventation-of-xss/39780376). You could (and should) implement input validation on your API though. The stricter you can make it the better. However, XSS is an output problem, it cannot be stopped on the input side. Still input validation is good practice and can help with all kinds of injections, not just XSS. – Gabor Lengyel Nov 01 '16 at 08:17