Often see in the project Ajax post data to the server without security tags, resulting in csrf attacks
Adding a security tag to asp.net mvc is simply adding Html.antiforgerytoken () to the form.
Html.antiforgerytoken () generates a pair of encrypted strings, stored in cookies and input respectively.
We also brought AntiForgeryToken in the Ajax post.
@model WebApplication1.Controllers.Person @{viewbag.title = "Index";}
An encrypted string placed inside a cookie
The code in the 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:controller {public ActionResult Index () {
return View (); [HttpPost] [Myvalidateantiforgerytoken] public actionresult Index (person p) {return Json (true, JSONREQUESTB Ehavior.
Allowget);
public class Person {public string Name {get; set;}
public int Age {get; set;} public class Myvalidateantiforgerytoken:authorizeattribute {public override void Onauthorization (Authorizationco
ntext 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 anti-counterfeiting mark from cookies and Headers//Here you can add Try-catch antiforgery.validate (cookievalue, request.
headers["__requestverificationtoken"]); else {new Validateantiforgerytokenattribute ().
Onauthorization (Filtercontext); }
}
}
}
}
This comment out 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")
}
})
Returns a status code of 500 by default.
Here to modify the security tag in Ajax
$ (function () {
//var token = $ (' [Name=__requestverificationtoken] ');
Get security token
var token = $ (' @Html. AntiForgeryToken () '). Val ();
var headers = {};
Security marking into the 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.
The above content is the entire description of this article, remember Ajax to take AntiForgeryToken to prevent CSRF attack, small partners in the use of the process found there is doubt, please give me a message, thank you!