CSRF what is a csrf
CSRF (Cross-site request forgery cross-site solicitation forgery, also known as "one click Attack" or session riding, usually abbreviated as CSRF or XSRF, is a malicious use of the site. It is important to note that the difference between CSRF and XSS is that CSRF is an attack on your site by other websites.
For more information on CSRF, see: https://baike.baidu.com/item/CSRF/2735433
The harm of two CSRF
After a brief overview of CSRF, let's take a look at the CSRF attack victim in a few steps.
The victim must complete two steps in turn:
1. Log on to trusted Web site A and generate cookies locally.
2. If you do not log out a, visit the dangerous website B.
At this time, dangerous site B has the victim in trust Site a login authentication cookie, assuming that the cookie does not expire or expire, then dangerous website B can initiate a fake request to obtain the victim on the trust site a information or without the victim's knowledge, the transfer of funds and so on.
How three MVC is preventing CSRF
The MVC framework is primarily prevented by adding @html.antiforgerytoken () and adding [Validateantiforgerytoken] to the action on the form.
The specific code is as follows:
1. Add @Html on the cshtml page. AntiForgeryToken ()
<section id= "LoginForm" >
@using (Html.BeginForm ("Login", "account", new {ReturnUrl = Viewbag.returnurl}, FormMethod.Post, new {@class = "form-ho Rizontal ", role =" form "}))
{
@Html. AntiForgeryToken ()
@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 Btn-default"/>
</div>
</div>
<p>
@Html. ActionLink ("Register as a new user", "register")
</p>
@* enable this item once the account acknowledgement is enabled for the password reset feature
<p>
@Html. ActionLink ("Forgot your password?", "Forgotpassword")
</p>*@
}
</section>
2. Add [Validateantiforgerytoken] on the appropriate 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 ("", "User name or password is invalid. ");
}
}
If something goes wrong when we go to this step, re-display the form
return View (model);
}
The principle of 3.MVC in preventing CSRF
The @Html. AntiForgeryToken () method will do two things on the browser:
1. Add a label to the page <input name= "__requestverificationtoken" type= "hidden" value= "ciphertext a"/>
2. generate a cookie named __requestverificationtoken on the browser with a value of "ciphertext B"
When the form form is submitted, the redaction A on the page and the redaction B of the browser are submitted to the server side, and the server side decrypts the ciphertext A and cipher B respectively, which is the same as the plaintext string after the decryption of the ciphertext A and cipher B, if the same, the validation passes.
So where is ciphertext a and cipher B come from, in fact, the above @html.antiforgerytoken () method randomly generated a bunch of plaintext, and then the plaintext encryption in the page and cookie, but the encryption of the ciphertext is different. Redaction a each refresh will be updated to a different ciphertext, but a browser process, the cookie cipher seems to be the same (you have tried several times in Firefox, interested students can try their own)
Four Ajax requests how to prevent CSRF
The above says how the MVC framework prevents CSRF, but is limited to form form submission, then the question is, in the general Ajax request, there is no form form submission, this time how to prevent csrf it? There are many good answers on the web. When I wrote this essay, I borrowed a lot of my predecessors ' methods.
Here's how I do this:
1. On the Global Share page, add the encryption text to generate the code:
@using (html.beginform (null, NULL, FormMethod.Post, new {id = "__ajaxantiforgeryform"}))
{
@Html. AntiForgeryToken ()
}
2. Tighten the Ajax Request method entry, write extended Ajax methods to avoid duplication of effort, be sure to 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. On the required post request, add [Validateantiforgerytoken]
[HttpPost]
[Validateantiforgerytoken]
Public Jsonresult Test (string teststring)
{
var trustedstring = Encoder.htmlencode (teststring);
Return Json (trustedstring);
}
4. Implement a specific AJAX request, which automatically brings ciphertext to the server, which is verified by the service-side features
$ (function () {
$ ("#test"). Click (Function ()
{
$.z_ajax (
{
URL: "/home/test",
Data: {teststring: ' 333333 '},
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, in writing this essay, referring to the ideas and crystallization of many predecessors. Not listed here, if there is any problem, please feel free to feedback.
The above cases use VS2013 automatically generated MVC5 site as parsing.
ASP. NET MVC and CSRF (cross-site scripting) attacks