在.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);
}