Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AntiXss protection Html model properties

Tags:

asp.net-mvc

Some of my model properties are marked by AllowHtml attribute. Is there any way to automatically apply AntiXss protection (i. e. filter only allowed tags) to these fields?

like image 556
SiberianGuy Avatar asked Nov 18 '12 15:11

SiberianGuy


1 Answers

First, afaik, nothing is built-in for that. But MVC allows to do such things easily via custom ModelBinders, you could define your

public class CustomAntiXssAttribute : Attribute { }

and decorate your properties with it (and even inherit from AllowHtmlAttribute if you wish). Then with a model binder you could add your specific anti-xss protection:

    public class CutstomModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.Attributes.OfType<CustomAntiXssAttribute>().Any())
            {
                var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
                var filteredValue = SOME_CUSTOM_FILTER_FUNCTION_HERE(valueResult.AttemptedValue);
                propertyDescriptor.SetValue(bindingContext.Model, filteredValue);
            }
            else // revert to the default behavior.
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
    }

Then inside that SOME_CUSTOM_FILTER_FUNCTION_HERE you could use what @Yogiraj suggested, or use a Regexp, or even apply HtmlAgilityPack-based filtering.

P.S. Don't forget to add ModelBinders.Binders.DefaultBinder = new CutstomModelBinder(); to Application_Start (I forgot :))

like image 113
Shaddix Avatar answered Oct 04 '22 19:10

Shaddix