简体   繁体   English

启用asp.net核心请求验证

[英]Enable asp.net core request validation

Am I missing something or asp.net core allows to post script tag in user text fields? 我错过了什么或asp.net核心允许在用户文本字段中发布脚本标记? In Previous versions of asp.net mvc I needed to allow it by [AllowHtml] attribute. 在asp.net mvc的早期版本中,我需要通过[AllowHtml]属性允许它。

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>

ASP.NET Core does not have a feature similar to Request validation , as Microsoft decided, that it's not a good idea. ASP.NET核心没有类似于Request验证的功能,正如微软认定的那样,这不是一个好主意。 For more information see the discussion on the ASP.NET Core issue ' Default middleware for request validation, like IIS has '. 有关更多信息,请参阅有关ASP.NET核心问题的讨论' 用于请求验证默认中间件,如IIS有 '。

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. 在Razor(.cshtml)中,您应输出用户提供的输入,如@Model.Content ,它对给定的字符串进行编码。

Please bear in mind that those escaping techniques might not work when the text that was output is not inside a Html part. 请记住,当输出的文本不在Html部分内时,那些转义技术可能不起作用。

So don't use @Html.Raw(..) unless you know that the data provided has been sanitized. 因此除非您知道所提供的数据已经过清理,否则不要使用@Html.Raw(..)

Supplement: 补充:

  • You might want to consider a Web Application Firewall (WAF) for a generic protection against malicious requests (eg XSS or SQL Injection). 您可能需要考虑使用Web应用程序防火墙 (WAF)来防范恶意请求(例如XSS或SQL注入)。
  • For protecting your users against an XSS attack you might also have a look at providing a Content Security Policy (CSP). 为了保护您的用户免受XSS攻击,您还可以查看提供内容安全策略 (CSP)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM