MVC默认禁止具有“潜在威胁”的HTML代码提交到后台 (演示)
如果要允许HTML标签等传往后台,最安全的方式是:在相关属性上添加[AllowHtml]特性:
[AllowHtml]
public string Body { get; set; }
而且HTML内容默认会被自动编码后呈现(演示)
要原本的(raw)呈现出HTML效果,需要使用@Html.Raw()
@Html.Raw(Model.Body)
这部分内容其实就两个关键:
我们演示更复杂的替换:
string[] allowedTags = new string[] { "p", "a", "img" };
string[] allowedProperties = new string[] { "style", "class" };
string fixedHtml = Regex.Replace(article.Body,
"(<.*?>)", //注意这个?:懒惰模式
match => fixTag(match, allowedTags, allowedProperties),
RegexOptions.IgnoreCase);
private string fixTag(Match tagMatch,
string[] allowedTags, string[] allowedProperties)
{
string tag = tagMatch.Value;
Match m = Regex.Match(tag,
//(?<tagName>exp))指定“组”的名称
@"</?(?<tagName>[^\s/]*)[>\s/]",
RegexOptions.IgnoreCase);
string tagName = m.Groups["tagName"].Value.ToLower();
如果是
if (Array.IndexOf(allowedTags, tagName) < 0)
{
return "";//理解:替换的是标签本身(比如p),还是?
private string fixProperty(Match propertyMatch, string[] allowedProperties)
{
string property = propertyMatch.Value;
Match m = Regex.Match(property,
//(?=exp):零宽断言,这里取属性名
@"(?<prop>\S*)(\s*)(?==\s*[" + "\"|'])",
RegexOptions.IgnoreCase);
string propertyName = m.Groups["prop"].Value.ToLower();
//对比fixTag的返回值
return Array.IndexOf(allowedProperties, propertyName) < 0 ?
string.Empty : property;
}
return Regex.Replace(tag,
@"\S+\s*=\s*[" + "\"|" + @" ']\S*\s*[" + "\"|']", //注意这别扭的写法
match => fixProperty(match, allowedProperties),
RegexOptions.IgnoreCase);
请同学们将上述方法封装成扩展方法,^_^
复习:CSRF的产生是因为:服务器无法区分用户究竟是不是从“我们指定的页面”发起的HTTP请求。
ASP.NET MVC提供了:
@Html.AntiForgeryToken()
可以生成一个hide input:
<input name="__RequestVerificationToken" type="hidden" value="Zta3V_I0tB8WeYdiPvoLeI13tLvLssD4HskPBxygDHH1RzrT3X2f5vlq_0ONaS85EqJwrDK9NKrTFIv5EdPN51pwAhu2og8w2SbvYcw71g41">和一个cookie:
__RequestVerificationToken:"a8pG2hMEnHb3NxQdbQhVGcMrP8QOtcH5UZ_uCnZxZ22mZ0wkfST8HsaaKOwiCVkVNS1RLVKt7bc_IgJrc_OJoZ0qwfIhasecPeYbJzrhUc41"
在Action上添加一个特性:
[ValidateAntiForgeryToken]ASP.NET就会根据接收到的hide input和cookie判断用户请求是不是自己生成的页面发起的。
演示:每次刷新页面都会生成不同的hide input和cookie
文章发布时,过滤用户输入:
且能防范防止CSFR攻击
多快好省!前端后端,线上线下,名师精讲
更多了解 加: