启用asp.net核心请求验证 [英] Enable asp.net core request validation
问题描述
我是否缺少某些内容或asp.net核心允许在用户文本字段中发布脚本标记?在asp.net mvc的早期版本中,我需要通过[AllowHtml]属性允许它.
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?
我可以自由地提交价值
<script src='http://test.com/hack.js'></script>
在表单发布期间.
型号:
using System.ComponentModel.DataAnnotations;
namespace Test.Models
{
public class TestModel
{
[MaxLength(500)]
public string Content { get; set; }
}
}
控制器:
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");
}
}
}
查看:
@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没有类似于请求验证不是一个好主意. 有关更多信息,请参见有关ASP.NET Core问题'用于验证请求的默认中间件的讨论,例如IIS具有'.
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'.
这意味着必须在入站模型上进行验证.而在Razor(.cshtml)中
您应该输出用户提供的输入,例如@Model.Content
,该输入对给定的字符串进行编码.
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.
请记住,当输出的文本不在HTML部件内时,这些转义技术可能不起作用.
Please bear in mind that those escaping techniques might not work when the text that was output is not inside a Html part.
因此,请勿不要使用@Html.Raw(..)
,除非您知道所提供的数据已被清理.
So don't use @Html.Raw(..)
unless you know that the data provided has been sanitized.
补充:
- 您可能要考虑使用 Web应用程序防火墙(WAF) 以获得针对恶意请求(例如XSS或SQL注入)的通用保护.
- 为了保护您的用户免受XSS攻击,您还可以查看 提供内容安全政策(CSP).
- 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).
这篇关于启用asp.net核心请求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!