什麼是CSRF攻擊?
CSRF(Cross-site request forgery跨站請求偽造,也被稱成為“one click attack”或者session riding,通常縮寫為CSRF或者XSRF,是一種對網站的惡意利用。儘管聽起來像跨站指令碼(XSS),但它與XSS非常不同,並且攻擊方式幾乎相左。XSS利用網站內的信任使用者,而CSRF則通過偽裝來自受信任使用者的請求來利用受信任的網站。與XSS攻擊相比,CSRF攻擊往往不大流行(因此對其進行防範的資源也相當稀少)和難以防範,所以被認為比XSS更具危險性。
詳細說明:http://baike.baidu.com/view/1609487.htm
CSRF攻擊發生的情境:
CSRF攻擊依賴下面的假定:
攻擊者瞭解受害者所在的網站
攻擊者的目標網站具有持久化授權cookie或者受害者具有當前會話cookie
目標網站沒有對使用者在網站行為的第二授權
Asp.net MVC 內建了對CSRF進行防禦的方法如下:
1.在View的Form表間中使用
<%=Html.AntiForgeryToken() %>
例如:
<% 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.d在對應的Action中用[ValidateAntiForgeryToken]進行標識:如下
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(Usr usr) { if (ModelState.IsValid) { var model = DB.Context.Single<Usr>(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); }
其實我們發現Asp.net MVC 幫我們做了很多。