Blazor Form - User Input Sanitization (<InputText>, <InputTextArea> etc)

Viewed 995

I am working on Blazor application where I have a form which take user input (form with some text boxes & text area). What is best approach to prevent it from cross site scripting and XSS attacks.

I am using Microsoft.AspNetCore.WebUtilities for other components for encoding and decoding html. Will encoding & decoding on user input suffice and prevent attacks, vulnerabilities etc.

Do I have to use some library such as Gans.XSS.HtmlSanitizer or is there some inbuilt feature in Blazor.

Thanks in Advance.

1 Answers

Since the inputs should be binding to a model inside an <EditForm> component, and that model is a class, can you use the inbuilt <DataAnnotationsValidator /> to get this done using a regular expression? you could build out your Model class with a Regex data annotation on the related properties:

using System.ComponentModel.DataAnnotations;

public class ModelToBindTo()
{
    [RegularExpression(@"[A-Za-z0-9 _.-]*")] //Check/tweak this before use, going from memory 
    public string PropertyToBindInputText { get; set;}
}

By binding to this and using the validator this should restrict any input characters that could get you into trouble, and you could run it against a regex again on the server side if needed to double check before persisting the data or doing anything else with it.

Further details on validator can be found here
Data Annotations reference can be found here

Related