Getting "potentially dangerous Request.Form value" from form despite security measures put in place

186 Views Asked by At

I have a contact form on my website that I've been getting errors of "A potentially dangerous Request.Form value was detected from the client" from for a while.

I have put in some measures to try to stop these including:

  • Adding in an anti-forgery token
  • Adding regex to the contact form model to prevent most special characters being posted
  • Adding Recapcha V3 to the form

Model:

[Required]
    [DataType(DataType.MultilineText)]
    [RegularExpression(@"^[a-zA-Z0-9!?£$'"",.&\-\s]+$", ErrorMessage = "Special characters are not allowed")]
    public string Message { get; set; }

View

    @using (Html.BeginForm(null, null, FormMethod.Post, new { controller = "home", action = "Contact"}))
{
    @Html.AntiForgeryToken()

    <div class="form">
        <div class="form_inner">
            <div class="fieldset">
                @Html.TextAreaFor(model => model.Message, 8, 25, new { required = "required" })
                @Html.ValidationMessageFor(model => model.Message)
            </div>           
            <footer>
                @Html.HiddenFor(model => model.GoogleCaptchaToken)
                <input type="submit" value="Send Email" class="btn btn_submit" />
            </footer>
        </div>
    </div>
}

Controller

    [HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(Contact model)
{
    if (ModelState.IsValid)
    {
        var isCaptchaValid = await IsCaptchaValid(model.GoogleCaptchaToken);

        if (isCaptchaValid)
        {
            _contactUsService.SendEmail(model);
        }
        else
        {
            ModelState.AddModelError("GoogleCaptcha", "The captcha is not valid");
        }            }

    return Redirect("/contact/thankyou");
}

However these so far have not been successful in stopping these error messages coming through.

The error never states the whole message that has been posted so I can't see what has triggered it. Is there something more I can add in to prevent these getting through, or so that I can see what is being posted from the form?

Thanks

1

There are 1 best solutions below

3
On

I think the problem you have is that the application rejects the value before getting to check your regular expression.

You can use the [AllowHtml] Attribute to allow the input to pass the value to the controller without being rejected for having dangerous characters.

But, you should check very carefully the value of the input as this attribute disables validation for that property.

You can read more about it here: AllowHtmlAttribute Class in Docs.Microsoft