asp.net mvc中html.antiforgerytoken()可以防止跨站请求伪造攻击,它跟xss(xss又叫css:cross-site-script),攻击不同,xss一般是利用站内信任的用户在网站内插入恶意的脚本代码进行攻击,而csrf则是伪造成受信任用户对网站进行攻击。
举个简单例子,譬如整个系统的公告在网站首页显示,而这个公告是从后台提交的,我用最简单的写法:
网站后台(home/index页面)设置首页公告内容,提交到homecontroller的text action
@using (html.beginform(text,home,formmethod.post)) { @:输入信息: } homecontroller的text action[httppost] public actionresult text() { viewbag.notice = request.form[notice].tostring(); return view(); }
填写完公告,提交,显示
此时提供给了跨站攻击的漏洞,csrf一般依赖几个条件
(1)攻击者了解受害者所在的站点
(2)攻击者的目标站点具有持久化授权cookie或者受害者具有当前会话cookie
(3)目标站点没有对用户在网站行为的第二授权此时
现在我们来开始模拟跨站请求,假设请求地址是http://localhost:25873/home/text,且也满足2,3的情况。
于是我新建一个antiforgerytext.html文件,内容如下
在这个html中加了一个隐藏的字段,name和id和网站要接收的参数名一样。
我点击了“黑掉这个网站”,呈现如下
这个就是利用了漏洞把首页的公告给改了,这就是一个简单的跨站攻击的例子。
mvc中通过在页面上使用 html.antiforgerytoken()配合在对应的action上增加[validateantiforgerytoken]特性来防止跨站攻击。
把上面的代码改成
@using (html.beginform(text,home,formmethod.post)) { @html.antiforgerytoken() @:网站公告: } [httppost] [validateantiforgerytoken] public actionresult text() { viewbag.notice = request.form[notice].tostring(); return view(); }
这样子我在antiforgerytext.html中点黑掉这个网站,再次发出请求
这就成功的防止了跨站攻击
参考资料:asp.net mvc中的@html.antiforgerytoken()防止跨站攻击http://www.ourcodelife.com/thread-49179-1-1.html