Often seen in the project Ajax post data to the server without security mark, causing CSRF attack
It is easy to add html.antiforgerytoken () to the form by adding a security tag to ASP.
Html.antiforgerytoken () generates a pair of encrypted strings that are stored in cookies and input.
We also take AntiForgeryToken in the Ajax post.
@model webapplication1.controllers.person@{viewbag.title = "Index";} Encrypted string placed in a cookie
Code in Controller
Using system;using system.collections.generic;using system.linq;using system.net;using System.Web;using System.web.helpers;using system.web.mvc;namespace webapplication1.controllers {public class Homecontroller:contro Ller {public ActionResult Index () {return View (); } [HttpPost] [Myvalidateantiforgerytoken] public actionresult Index (person p) {Retur N Json (True, jsonrequestbehavior.allowget); }} public class Person {public string Name {get; set;} public int Age {get; set;} } public class Myvalidateantiforgerytoken:authorizeattribute {public override void Onauthorization (Aut Horizationcontext filtercontext) {var request = FilterContext.HttpContext.Request; if (Request. HttpMethod = = WebRequestMethods.Http.Post) {if (Request. IsajaxrequesT ()) {var Antiforgerycookie = Request. Cookies[antiforgeryconfig.cookiename]; var cookievalue = Antiforgerycookie! = null? AntiForgeryCookie.Value:null; Verify the security mark from cookies and Headers///Here you can add Try-catch antiforgery.validate (Cookievalue, req Uest. headers["__requestverificationtoken"]); } else {new Validateantiforgerytokenattribute () . Onauthorization (Filtercontext); } } } } }Here comment out the Ajax in the security tag in the request
$ ("#save"). Click (function () { $.ajax ({ type: ' POST ', URL: '/home/index ', cache:false, // Headers:headers, data: {Name: "Yangwen", Age: "1"}, success:function (data) { alert (data) }, error:function () { alert ("Error") } })
A status code of 500 is returned by default.
Here to modify the security tag in Ajax
$ (function () { //var token = $ (' [Name=__requestverificationtoken] '); Get the security Mark var token = $ (' @Html. AntiForgeryToken () '). Val (); var headers = {}; Security mark put into headers //can also put the security mark into the data headers["__requestverificationtoken" = token+ 11111111111111111111111111111111111; $ ("#save"). Click (function () { $.ajax ({ type: ' POST ', URL: '/home/index ', cache:false, Headers:headers, data: {Name: "Yangwen", Age: "1"}, success:function (data) { alert (data) },
error:function () { alert ("Error")})})
is also a 500 status code.
Add AntiForgeryToken in Ajax to prevent CSRF attacks