Add AntiForgeryToken in Ajax to prevent CSRF attacks

Source: Internet
Author: User

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

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.