Protecting ASP.NET MVC 5 application from XSS

13,716

When posting any input field with HTML in it ASP.NET MVC will throw an exception. You need to add AllowHtml attribute on a particular input. For example:

public class Post
{
  public string Title {set;get;}
  [AllowHtml]
  public string Content { set;get;}
}

When displaying this field you need to use @ as per docs:

https://docs.microsoft.com/en-us/aspnet/core/security/cross-site-scripting

The Razor engine used in MVC automatically encodes all output sourced from variables, unless you work really hard to prevent it doing so. It uses HTML Attribute encoding rules whenever you use the @ directive. As HTML attribute encoding is a superset of HTML encoding this means you don't have to concern yourself with whether you should use HTML encoding or HTML attribute encoding. You must ensure that you only use @ in an HTML context, not when attempting to insert untrusted input directly into JavaScript. Tag helpers will also encode input you use in tag parameters.

Share:
13,716
LP13
Author by

LP13

Updated on June 05, 2022

Comments

  • LP13
    LP13 about 2 years

    I want to protect my ASP.NET MVC 5 application from Cross Site Scripting (XSS). I have gone through several articles and SO post. The ideal option is to encode the input and also encode when input is redisplayed.

    However, MVC, by default, prevents any requests containing HTML markup, in order to avoid XSS attacks. By default ASP.NET 4.5 throws an exception if potentially dangerous content is detected in the request.

    In certain legitimate cases it is perfectly acceptable for the user to submit markup. But my application there is NO such case where user would need to enter markup.

    If i enter any markup in input field, asp.net throws exception as expected. Having said that do i really still need to encode input or it is already taken care by asp.net 5?