ASP. Net MVC method to prevent CSRF

Source: Internet
Author: User
Tags form post

Html.antiforgerytoken () in MVC is a measure to prevent cross-site request forgery (Csrf:cross-site requests forgery) attacks, which are called XSS (XSS, also known as Css:cross-site-script ), the attack is different, XSS is generally the use of trusted users in the site to insert malicious script code to attack, and CSRF is forged into a trusted user to attack the site.

To give a simple example, such as the entire system of announcements on the homepage of the site, and this announcement is submitted from the background, I use the simplest wording:

Site background (Home/index page) set the first page announcement content, submitted to HomeController's text Action

@using (Html.BeginForm ("Text", "Home", FormMethod.Post))
{
@: Website announcement: <input type= "text" name= "Notice" id= "Notice"/>
<input type= "Submit" value= "Submit"/>
}

HomeController's text Action

[HttpPost]
Public ActionResult Text ()
{
Viewbag.notice = request.form["Notice"]. ToString ();
return View ();
}

Fill out the announcement, submit, show

This provides a vulnerability to cross-site attacks, and CSRF generally relies on several conditions

(1) The attacker knows the site where the victim resides

(2) The attacker's target site has a persistent authorization cookie or the victim has a current session cookie

(3) The target site does not have a second authorization for the user's behavior on the site at this time

See http://baike.baidu.com/view/1609487.htm for details.

Now suppose I know the address of the website I am attacking, for example, Http://localhost:6060/Home/Text, and also to meet the 2,3 situation.

So I created a new antiforgerytext.html file with the following content:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<form name= "Badform" method= "post" action= "Http://localhost:6060/Home/Text" >
<input type= "hidden" name= "Notice" id= "Notice" value= "Your site was hacked by me. "/>
<input type= "Submit" value= "Black out this site"/>
</form>
</body>

A hidden field is added to this HTML, and the name and ID are the same as the name of the parameter to be received by the Web site.

I clicked the "black out of this site" and presented the following

This is the use of loopholes in the first page of the announcement to change, this is a simple cross-site attack example.

In MVC, you can prevent cross-site attacks by adding [Validateantiforgerytoken] features to the corresponding action by using Html.antiforgerytoken () Mates on the page.

Change the code above to

@using (Html.BeginForm ("Text", "Home", FormMethod.Post))
{
@Html. AntiForgeryToken ()
@: Website announcement: <input type= "text" name= "Notice" id= "Notice"/>
<input type= "Submit" value= "Submit"/>
}

The corresponding action

[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Text ()
{
Viewbag.notice = request.form["Notice"]. ToString ();
return View ();
}

In this way, I "hacked this site" at the midpoint of the antiforgerytext.html, and it would appear

This prevents cross-site attacks.

The Html.antiforgerytoken () on the page will give the visitor a default cookie named __requestverificationtoken
To verify that one comes from the form post, you also need to add the [Validateantiforgerytoken] attribute on the target action, which is a validation filter,
It mainly examines

(1) Whether the requested cookie contains a antiforgery name of the contract

(2) Whether the request has a request.form["agreed antiforgery name"], the agreed antiforgery name of the cookie and the Request.Form value match

It mainly involves static class antiforgery in System.Web.WebPages.dll.
Html.antiforgerytoken () invokes the Gethtml method of the Antiforgery static class, which produces a random value that is then stored in the hidden field of the client cookie and the page, respectively,

(1) Request.cookies[antiforgerytokenname] (default is also request.cookies["__requestverificationtoken"])

(2) HiddenField on the page

<input name= "__requestverificationtoken" type= "hidden" value= "9rulmyvsh6emcfn9tn/ wrwag07eroravaetn9hhmxkkmmdbr8jlw5dkdvnzbj9siqhegyl1w4rsb141lnxmp2ahv0qp1lelpeukqfcufyoxrm/ Efpsjjzavykmzn15vegfmkkmgfj5a1ufhzfaw2azgen38x9lt0ofsoca7emvu= "/>

The name of the key of the cookie and the name of the page hidden field are the same, the default is "__requestverificationtoken", if provided Applicationpath, it is by "__ Requestverificationtoken "and a treated applicationpath composition.

The controller side is validated by adding the [Validateantiforgerytoken] feature on the action,
Validateantiforgerytokenattribute inherits the FilterAttribute and Iauthorizationfilter by passing the anonymous delegate method,

The delegate invokes the Validate method of the Antiforgery class to implement validation.

The Validate method mainly verifies that the values of request.cookies[antiforgerytokenname] and <input name=antiforgerytokenname ...> two are the same,

If the page does not have <input name=antiforgerytokenname, or two values are not equal, an exception is thrown.

The disadvantages of using this method are:

1. This approach is dependent on cookies, which can be invalidated if the client prohibits cookies.

2. This method is valid for a POST request and is not valid for a GET request

3. For Ajax requests, the MVC framework does not automatically pass cookies and hidden fields. You need to implement your own transfer and read.

ASP. Net MVC method to prevent CSRF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.