I am trying to sanitize the requests body coming to an Asp.net (.Net 4.6) application with WebAPI 2 using OWIN/Katana. However, after modifying the body I am still getting the original text inside the API method.
Example input whwc8'-alert(123)-'mg763
After Sanitizing It will look like whwc8-alert|123|-
mg763
(I know that this is not the best way to prevent XSS, I am properly encoding the text at the client side. This is just because my customer is hell-bent on disabling the set of special characters that they have in a list).
My Startup class:
Startup.cs
public class Startup
{
private static ILog Log;
public void Configuration(IAppBuilder app)
{
app.Use<SanitizerMiddleware>();
app.MapSignalR();
app.UseWebApi(WebApiConfig.Register());
}
}
The sanitizer Middle-ware
public class SanitizerMiddleware : OwinMiddleware
{
OwinMiddleware _next;
public SanitizerMiddleware(OwinMiddleware next) :base(next)
{
_next = next;
}
public async override Task Invoke(IOwinContext context)
{
await Sanitize(context);
await Next.Invoke(context);
}
public async Task Sanitize(IOwinContext context)
{
if (context.Request.Method == "POST")
{
StreamReader reader = new StreamReader(context.Request.Body);
string text = reader.ReadToEnd();
text = new HtmlSanitizer().Sanitize(text).Replace("'", "`").Replace("(", "|").Replace(")", "|");
byte[] requestData = Encoding.UTF8.GetBytes(text);
context.Request.Body=new MemoryStream(requestData);
}
}