How to use AntiForgeryToken in ajax to prevent CSRF attacks
Editor to share with you how to use AntiForgeryToken in ajax to prevent CSRF attacks, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
It is often seen that ajax post data is not marked to the server in a project, resulting in CSRF attacks.
Adding an anti-counterfeiting tag to Asp.net Mvc is as simple as adding Html.AntiForgeryToken () to the form.
Html.AntiForgeryToken () generates a pair of encrypted strings that are stored in Cookies and input, respectively.
We also bring AntiForgeryToken in ajax post.
@ model WebApplication1.Controllers.Person@ {ViewBag.Title = "Index" } Index Persen @ Html.ValidationSummary (true, ", new {@ class =" text-danger "}) @ Html.LabelFor (model = > model.Name, htmlAttributes: new {@ class =" control-label col-md-2 "}) @ Html.EditorFor (model = > model.Name, new {htmlAttributes = new {@ class =" form-control "}}) @ Html.ValidationMessageFor (model = > model.Name," New {@ class = "text-danger"}) @ Html.LabelFor (model = > model.Age, htmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.Age, new {htmlAttributes = new {@ class = "form-control"}}) @ Html.ValidationMessageFor (model = > model.Age, "" New {@ class = "text-danger"}) $(function () {/ / var token = $('[name=__RequestVerificationToken]')) / / get the anti-counterfeiting mark var token = $('@ Html.AntiForgeryToken ()'). Val (); var headers = {}; / / put the anti-counterfeiting mark into headers / / you can also put the anti-counterfeiting mark into data headers ["_ _ RequestVerificationToken"] = token ("# 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")});})})
Encrypted string placed in cookies
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: 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.Cookies [AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie! = null? AntiForgeryCookie.Value: null; / / verify security marks from cookies and Headers / / you can add try-catch AntiForgery.Validate (cookieValue, request.Headers ["_ _ RequestVerificationToken"]);} else {new ValidateAntiForgeryTokenAttribute () .OnAuthorization (filterContext);}
Comment out here that the anti-counterfeiting mark in ajax is 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")});})
The 500 status code is returned by default.
Modify the anti-counterfeiting mark in ajax here
$(function () {/ / var token = $('[name=__RequestVerificationToken]')); / / get the anti-counterfeiting tag var token = $('@ Html.AntiForgeryToken ()'). Val (); var headers = {}; / / the anti-counterfeiting tag can also be put into headers / / you can also put the anti-counterfeiting tag 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's also a status code of 500.
The above is all the contents of the article "how to use AntiForgeryToken to prevent CSRF attacks in ajax". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!