Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

c# - Enable asp.net core request validation

Am I missing something or asp.net core allows to post script tag in user text fields? In Previous versions of asp.net mvc I needed to allow it by [AllowHtml] attribute.

Is there a way how enable validation agains potentially dangerous values?

I'm free to submit value like

<script src='http://test.com/hack.js'></script>

during form post.

Model:

using System.ComponentModel.DataAnnotations;

namespace Test.Models
{
    public class TestModel
    {
        [MaxLength(500)]
        public string Content { get; set; }
    }
}

Controller:

using Microsoft.AspNetCore.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var model = new TestModel { Content = "Test" };
            return View();
        }

        [HttpPost]
        public IActionResult Index(TestModel model)
        {
            if(!ModelState.IsValid)
                return View(model);

            return Content("Success");
        }
    }
}

View:

@model TestModel

<form asp-action="Index" asp-controller="Home" method="post">
    <div asp-validation-summary="All"></div>
        <label asp-for="Content">Content<strong>*</strong></label>
        <span asp-validation-for="Content"></span>
        <input asp-for="Content" type="text" />
    </div>
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ASP.NET Core does not have a feature similar to Request validation, as Microsoft decided, that it’s not a good idea. For more information see the discussion on the ASP.NET Core issue 'Default middleware for request validation, like IIS has'.

That means that validation has to take place on the inbound model. And that in the Razor (.cshtml) you should output user provided input like @Model.Content, which encodes the given string.

Please bear in mind that those escaping techniques might not work when the text that was output is not inside a Html part.

So don't use @Html.Raw(..) unless you know that the data provided has been sanitized.

Supplement:

  • You might want to consider a Web Application Firewall (WAF) for a generic protection against malicious requests (e.g. XSS or SQL Injection).
  • For protecting your users against an XSS attack you might also have a look at providing a Content Security Policy (CSP).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...