前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Html.AntiForgeryToken 防止伪造提交

Html.AntiForgeryToken 防止伪造提交

作者头像
javascript.shop
发布2019-09-04 16:43:10
1.3K0
发布2019-09-04 16:43:10
举报
文章被收录于专栏:杰的记事本杰的记事本

In this tutorial, I am not going to discuss the concept in-depth since they have done such a fantastic job. Instead, I want to show how you can easily incorporate the Html.AntiForgeryToken HtmlHelper Method and [ValidateAntiForgeryToken] Attribute in the sample code from our first meeting:Introduction to ASP.NET MVC Screencast and Sample Code.

This is really a two-step process:

Add the [ValidateAntiForgeryToken] Attribute to any Post Action Methods.Add the Html.AntiForgeryToken() HtmlHelper Method to any forms posting back to the website.

Let’s just do this to the Edit Action Method in the ContactsController in this tutorial.

[ValidateAntiForgeryToken] Attribute

The ValidateAntiForgeryToken Attribute in the ASP.NET MVC Framework is an IAuthorizationFilter which is guaranteed to run before any other filters. You add it to your post Action Methods as such:

[AcceptVerbs(HttpVerbs.Post)]

[ValidateAntiForgeryToken]

publicActionResultEdit(Contactcontact)

{

    try

    {

        if (!ModelState.IsValid)

            returnView(contact);

        _db.Contacts.Attach(contact, true);

        _db.SubmitChanges();

        returnRedirectToAction(“List”);

    }

    catch

    {

        returnView(contact);

    }

}

The ValidateAntiForgeryToken Attribute does some voodoo magic in the background. It checks to see that the cookie and hidden form field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException:

You can obviously clean that exception up, but the important point is that if the cookie and form field do not exist or match the action method is not executed for security reasons. This is a good thing!

Html.AntiForgeryToken HtmlHelper Method

As mentioned before, we need to add the Html.AntiForgeryToken Method to the forms so that a cookie is added on the client and a hidden form field is added to the form itself. This is as simple as:

You will notice the hidden form field in the HTML source:

The Html.AntiForgeryToken Method will also add a cookie on your machine matching the same value in the hidden form field. It is the cookie and the hidden form field value that the ValidateAntiForgeryToken Attribute is checking.

Conclusion

Pretty simple way to protect your website against Cross-Site Request Forgery Attacks in the ASP.NET MVC Framework.

You can add this code yourself by downloading the Tampa MVC Developer Group Screencast and sample code based on our first meeting.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011年5月16日2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档