温馨提示×

.net如何防御csrf攻击

九三
284
2021-01-13 18:43:11
栏目: 网络安全

.net如何防御csrf攻击

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

}



0