MVC中防止CSRF攻击
使用AntiForgeryToken令牌,在ASP.NET的核心中为我们提供了一个用来检测和组织CSRF攻击的令牌。
只要在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击。
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="保存" />
</p>
</fieldset>
}
相应的我们要在Controller中也要加入[ValidateAntiForgeryToken]过滤特性。
该特性表示检测服务器请求是否被篡改。
注意:该特性只能用于post请求,get请求无效。
[ValidateAntiForgeryToken]//[ValidateAntiForgeryToken(Salt ="aa")]
[HttpPost]
public ActionResult Edit(int id, Person person)
{
try
{
// 数据库操作代码
return RedirectToAction("Success",person);
}
catch
{
return View();
}
}