Add AntiForgeryToken in Ajax to prevent CSRF attacks

Source: Internet
Author: User
Tags csrf attack

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";}"Form1"> <divclass="Form-horizontal"> @Html. ValidationSummary (true,"",New{@class ="Text-danger" })        <divclass="Form-group">@Html. Labelfor (Model= Model. Name, Htmlattributes:New{@class ="Control-label col-md-2" })            <divclass="col-md-10">@Html. Editorfor (Model= Model. Name,New{htmlattributes =New{@class ="Form-control"}}) @Html. validationmessagefor (Model= Model. Name,"",New{@class ="Text-danger" })            </div> </div> <divclass="Form-group">@Html. Labelfor (Model= Model. Age, Htmlattributes:New{@class ="Control-label col-md-2" })            <divclass="col-md-10">@Html. Editorfor (Model= Model. Age,New{htmlattributes =New{@class ="Form-control"}}) @Html. validationmessagefor (Model= Model. Age,"",New{@class ="Text-danger" })            </div> </div> <divclass="Form-group"> <divclass="col-md-offset-2 col-md-10"> <input type="Button"Id="Save"Value="Create" class="btn Btn-default"/> </div> </div> </div></form><script src="~/scripts/jquery-1.10.2.min.js"></script><script src="~/scripts/jquery.validate.min.js"></script><script src="~/scripts/jquery.validate.unobtrusive.min.js"></script><script type="Text/javascript">$ (function () {//var token = $ (' [Name=__requestverificationtoken] '); //Get Security Tags        varToken = $ ('@Html. AntiForgeryToken ()'). Val (); varheaders = {}; //anti-counterfeiting tags put into headers//You can also put the security tag into the dataheaders["__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:f Unction () {alert ("Error")                }            }); })    })</script>

Encrypted string placed in a cookie

Code in Controller

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingsystem.web;usingSystem.Web.Helpers;usingSYSTEM.WEB.MVC;namespaceWebapplication1.controllers { Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } [HttpPost] [Myvalidateantiforgerytoken] Publicactionresult Index (person p) {returnJson (true, Jsonrequestbehavior.allowget); }        }     Public classPerson { Public stringName {Get;Set; }  Public intAge {Get;Set; } }     Public classMyvalidateantiforgerytoken:authorizeattribute { Public Override voidonauthorization (AuthorizationContext filtercontext) {varRequest =filterContext.HttpContext.Request; if(Request. HttpMethod = =WebRequestMethods.Http.Post) {if(Request. Isajaxrequest ()) {varAntiforgerycookie =request.                    Cookies[antiforgeryconfig.cookiename]; varCookievalue = Antiforgerycookie! =NULL?Antiforgerycookie.value:NULL; //verification of anti-counterfeiting marks from cookies and Headers//You can add try-catch here .Antiforgery.validate (Cookievalue, request.) headers["__requestverificationtoken"]); }                Else                    {                    NewValidateantiforgerytokenattribute ().                    Onauthorization (Filtercontext); }                }            }        }    }

Here comment out the Ajax in the security tag in the request

A status code of 500 is returned by default.

Here to modify the security tag in Ajax

$ (function () {//var token = $ (' [Name=__requestverificationtoken] '); //Get Security Tags        varToken = $ ('@Html. AntiForgeryToken ()'). Val (); varheaders = {}; //anti-counterfeiting tags put into headers//You can also put the security tag into the dataheaders["__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:f Unction () {alert ("Error")                }            }); })    })

is also a 500 status code.

Original address: https://www.cnblogs.com/soundcode/p/4884260.html

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.