Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 505
ZKS Avatar asked Sep 11 '26 15:09

ZKS


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

like image 147
Nik P Avatar answered Sep 14 '26 11:09

Nik P