【MVC整理】4.Asp.net MVC 如何防止CSRF攻擊

來源:互聯網
上載者:User

什麼是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 幫我們做了很多。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.