在.net项目中防御csrf攻击的方法
1首先,在.net项目添加以下代码;
<% using (Html.BeginForm("Login", "Admin", FormMethod.Post))
{ %>
<%=Html.AntiForgeryToken() %>
<%= Html.ValidationSummary(true, "登录不成功。请更正错误并重试。") %>
<div>
<fieldset>
<legend>帐户信息</legend>
<div class="editor-label">
<%= Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(m => m.UserName)%>
<%= Html.ValidationMessageFor(m => m.UserName)%>
<label id="UserNameTip"></label>
</div>
<div class="editor-label">
<%= Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%= Html.PasswordFor(m => m.Password) %>
<%= Html.ValidationMessageFor(m => m.Password) %>
</div>
<p>
<input type="submit" value="登录" />
</p>
</fieldset>
</div>
<% } %>
2.代码添加好后,在对应的Action中用[ValidateAntiForgeryToken]进行标识即可;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Usr usr)
{
if (ModelState.IsValid)
{
var model = DB.Context.Single(p => p.SystemUser == true && p.UserName == usr.UserName && p.Password == usr.Password);
if (model != null)
{
authenticate.Login(usr.UserName, usr.Role);
return RedirectToAction("UserList", "Admin");
}
else
{
ModelState.AddModelError("", "提供的用户名或密码不正确。");
}
}
return View(usr);
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>