Remember to include the AntiForgeryToken in ajax to prevent CSRF attacks. ajaxantiforgery

Source: Internet
Author: User

Remember to include the AntiForgeryToken in ajax to prevent CSRF attacks. ajaxantiforgery

It is often seen that no anti-counterfeit mark is added to the server for ajax post data in the project, resulting in CSRF attacks.

Adding anti-counterfeit tags to Asp.net Mvc is easy to add Html. AntiForgeryToken () to the form.

Html. AntiForgeryToken () generates an encrypted string, which is stored in Cookies and inputs respectively.

We also include the AntiForgeryToken in ajax post.

@ Model WebApplication1.Controllers. person @ {ViewBag. title = "Index ";} 

Encrypted string placed in cookies

Controller code

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, JsonRequestBehavior. allowGet );} Public class Person {public string Name {get; set;} public int Age {get; set ;}} public class MyValidateAntiForgeryToken: AuthorizeAttribute {public override void OnAuthorization (AuthorizationContext filterContext) {var request = filterContext. httpContext. request; if (request. httpMethod = WebRequestMethods. http. post) {if (request. isAjaxRequest () {var antiForgeryCookie = request. coo Kies [AntiForgeryConfig. CookieName]; var cookieValue = antiForgeryCookie! = Null? AntiForgeryCookie. value: null; // verify the anti-counterfeit flag from cookies and Headers. // try-catch AntiForgery can be added here. validate (cookieValue, request. headers ["_ RequestVerificationToken"]);} else {new ValidateAntiForgeryTokenAttribute (). onAuthorization (filterContext );}}}}}

Comment out the anti-pseudomark-in request in ajax

$("#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")  } });})

By default, status code 500 is returned.

Modify the anti-counterfeit mark in ajax

$ (Function () {// var token = $ ('[name =__ RequestVerificationToken]'); // obtain the anti-counterfeit flag var token = $ ('@ Html. antiForgeryToken ()'). val (); var headers ={}; // put the anti-counterfeit Mark into headers // You can also put the anti-counterfeit Mark into 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 ")}});})})

It is also a status code of 500.

The above content is all described in this article. Remember to include the AntiForgeryToken in ajax to prevent CSRF attacks. If you have any questions during usage, please leave a message for me. Thank you!

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.