Remember to take antiforgerytoken in Ajax to prevent CSRF attacks _ajax related

Source: Internet
Author: User
Tags csrf attack

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!

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.