ASP. net mvc and CSRF (Cross-Site Scripting) attacks, mvccsrf

Source: Internet
Author: User
Tags actionlink csrf attack

ASP. net mvc and CSRF (Cross-Site Scripting) attacks, mvccsrf
What is CSRF?

CSRF (Cross-site request forgery, also known as "one click attack" or session riding, usually abbreviated as CSRF or XSRF, is a type of malicious use of websites. Note that CSRF is different from XSS. CSRF is an attack on your website from other websites.

For more information about CSRF, see: https://baike.baidu.com/item/CSRF/2735433

 

Hazards of CSRF

After a brief understanding of CSRF, let's take a few steps to identify the CSRF attack victims.

The victim must complete two steps in sequence:

1. log on to trusted website A and generate A Cookie locally.

2. Access dangerous website B without logging out of account.

At this time, dangerous website B has the login verification cookie that the victim trusts website A. If the Cookie does not expire or expires, then dangerous website B can initiate A fake request, attackers can transfer funds from A trusted website A or without the knowledge of the victim.

 

3. How does MVC prevent CSRF attacks?

The MVC framework is mainly prevented by adding @ Html. AntiForgeryToken () to the form and adding [ValidateAntiForgeryToken] to the action.

The Code is as follows:

1. Add @ Html. AntiForgeryToken () to the cshtml page ()

<Section id = "loginForm">
@ Using (Html. beginForm ("Login", "Account", new {ReturnUrl = ViewBag. returnUrl}, FormMethod. post, new {@ class = "form-horizontal", role = "form "}))
{
@ Html. AntiForgeryToken ()
<H4> log on with a local account. </H4>
<Hr/>
@ Html. ValidationSummary (true, "", new {@ class = "text-danger "})
<Div class = "form-group">
@ Html. LabelFor (m => m. Email, new {@ class = "col-md-2 control-label "})
<Div class = "col-md-10">
@ Html. TextBoxFor (m => m. Email, new {@ class = "form-control "})
@ Html. ValidationMessageFor (m => m. Email, "", new {@ class = "text-danger "})
</Div>
</Div>
<Div class = "form-group">
@ Html. LabelFor (m => m. Password, new {@ class = "col-md-2 control-label "})
<Div class = "col-md-10">
@ Html. PasswordFor (m => m. Password, new {@ class = "form-control "})
@ Html. ValidationMessageFor (m => m. Password, "", new {@ class = "text-danger "})
</Div>
</Div>
<Div class = "form-group">
<Div class = "col-md-offset-2 col-md-10">
<Div class = "checkbox">
@ Html. CheckBoxFor (m => m. RememberMe)
@ Html. LabelFor (m => m. RememberMe)
</Div>
</Div>
</Div>
<Div class = "form-group">
<Div class = "col-md-offset-2 col-md-10">
<Input type = "submit" value = "login" class = "btn-default"/>
</Div>
</Div>
<P>
@ Html. ActionLink ("registering as a new user", "Register ")
</P>
@ * Enable account confirmation once for the password reset function
<P>
@ Html. ActionLink ("Forgot your password? "," ForgotPassword ")
</P> *@
}
</Section>

2. Add the [ValidateAntiForgeryToken] to the corresponding action method.

 

//
// POST:/Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
Public async Task <ActionResult> Login (LoginViewModel model, string returnUrl)
{
If (ModelState. IsValid)
{
Var user = await UserManager. FindAsync (model. Email, model. Password );
If (user! = Null)
{
Await SignInAsync (user, model. RememberMe );
Return RedirectToLocal (returnUrl );
}
Else
{
ModelState. AddModelError ("", "the user name or password is invalid. ");
}
}

// If an error occurs in a certain part of the process, the form is displayed again.
Return View (model );
}

 

3. The principle of MVC in preventing CSRF

@ Html. AntiForgeryToken () method will do two things in the browser:

1. Add A label <input name = "_ RequestVerificationToken" type = "hidden" value = "A"/> to the page.

2. Generate a Cookie named _ RequestVerificationToken in the browser with the value of "ciphertext B"

When A form is submitted, the ciphertext A on the page and the ciphertext B of the browser are submitted to the server, and the server decrypts the ciphertext A and the ciphertext B respectively, check whether the plaintext strings decrypted by ciphertext A and ciphertext B are the same. If they are the same, the verification passes.

So where does ciphertext A and ciphertext B come from? It is actually the above @ Html. the AntiForgeryToken () method randomly generates a string of plaintext, and then encrypts the plaintext in the page and cookie, but the encrypted ciphertext is different. Ciphertext A is updated to A different ciphertext each time it is refreshed, but the ciphertext of the COOKIE does not change in the process of A browser (I tried it several times in firefox, if you are interested, try it yourself)

4. How can AJAX requests prevent CSRF attacks?

As mentioned above, how does the MVC Framework prevent CSRF, but it is only limited to FORM form submission? So the question is, how can we prevent CSRF from being used in normal ajax requests without FORM submission? There are many good answers on the Internet. When I wrote this article, I also used a lot of methods from my predecessors.

The following describes my methods:

 

1. on the global sharing page, add the ciphertext Generation Code:

@ Using (Html. BeginForm (null, null, FormMethod. Post, new {id = "_ AjaxAntiForgeryForm "}))
{
@ Html. AntiForgeryToken ()
}

2. Tighten the ajax Request Method entry and write the extended ajax method to avoid repeated work. Pay attention to the yellow mark.

$. Extend ({
Z_ajax: function (request ){
Var form = $ ('#__ AjaxAntiForgeryForm ');
Var antiForgery = $ ("input [name = '_ RequestVerificationToken']", form). val ();
Var data = $. extend ({__ RequestVerificationToken: antiForgery}, request. data );
Request = $. extend ({
Type: "POST ",
DataType: "json ",
ContentType: 'application/x-www-form-urlencoded; charset = UTF-8 ',
}, Request );
Request. data = data;

$. Ajax (request );
}

3. Add the [ValidateAntiForgeryToken] to the required POST request.

[HttpPost]
[ValidateAntiForgeryToken]
Public JsonResult Test (string testString)
{
Var trustedString = Encoder. HtmlEncode (testString );
Return Json (trustedString );
}

4. Implement a specific ajax request. The request will automatically bring the ciphertext to the server, which is verified by the server's features.

$ (Function (){
$ ("# Test"). click (function ()
{
$. Z_ajax (
{
Url: "/Home/Test ",
Data: {testString: '000000 '},
Error: function (request, textStatus, errorThrown ){
Console. log (request, textStatus, errorThrown );
},
Success: function (response)
{
Alert (123 );
}
});
})
})

 

After the above explanation, we should have a certain understanding of MVC to prevent CSRF.

As mentioned above, when writing this essay, I have referred to the ideas and achievements of many predecessors. I will not list them here. If you have any questions, please feel free to give your feedback.

The above case uses the MVC5 Site Automatically Generated by VS2013 for resolution.

 

Related Article

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.