Stopping XSS when using WebAPI

后端 未结 4 1507
醉酒成梦
醉酒成梦 2021-02-06 07:12

I have a controller which accepts

public class MyModel
{
   [MaxLength(400)]
   public string Message { get; set; }
}

I have a WebApi Post Acti

4条回答
  •  滥情空心
    2021-02-06 07:30

    There are two main schools of thought to protect against XSS attacks.

    • Output encoding
    • Input validation

    For output encoding, Server.HtmlEncode(p.message) should do the trick (so what you have currently in your example will work, don't need to do the Regex replace if you don't want to. The output encoding will prevent XSS). Here I am assuming you want to do HTML encoding and not Url encoding or the like.

    Looks like you are using the .NET MVC framework. You could use DataAnnotations to preform white-list validation (allow only safe characters) versus black-listing. I would look at using the RegularExpressionAttribute. For example:

    public class MyModel
    {
       [RegularExpression(@"^[a-zA-Z''-'\s]{1,400}$", ErrorMessage = "Characters are not allowed.")]
       public string Message { get; set; }
    }
    

    Hope this helps.

提交回复
热议问题