ASP. NET MVC Ajax forgery request

Source: Internet
Author: User

1. Preface

CSRF (Cross-site request forgery) cross-site solicitation forgery, the ASP. NET MVC application improves the user experience by using AJAX requests, browser developer tools can be at a glance at the mountains small, it is easy to forge a request to attack the application, thereby leaking core data, Cause security issues. Microsoft's own antiforgerytoken can be solved, and the syntax is simple (the AJAX request is initiated by a string that is passed to the background, and then verified in the filter)

2. The scene is as follows

To validate a request from a form post, you also need to add a custom [AntiForgeryToken] attribute on the target action, which describes the custom attribute usage

    /// <summary>    ///Home Page/// </summary>     Public classHomecontroller:controller {/// <summary>        ///the user is logged in to 111111/// </summary>        /// <returns></returns>         PublicActionResult Index () {            returnView (); }        /// <summary>        ///Your Application Description page. /// </summary>        /// <returns></returns>         PublicActionResult About () {Viewbag.message="Your Application description page.";            returnView (); }        /// <summary>        ///Your Contact page. /// </summary>        /// <param name= "name" >name</param>        /// <returns></returns>         PublicActionResult Contact (stringname) {Viewbag.message="Your Contact page.";            returnView (); }        /// <summary>        ///         /// </summary>        /// <returns></returns>         PublicActionResult person () {returnView (); }        /// <summary>        ///         /// </summary>        /// <param name= "name" ></param>        /// <param name= "age" ></param>        /// <returns></returns>[HttpPost] [AntiForgeryToken] PublicActionResult UserInfo (stringName,stringAge ) {            returnJson (Name +Age ); }    }

How to prevent in front-end HTML?

A syntactic sugar solves all problems by using Html.antiforgerytoken () on an Html page or script and assigning it to Ajax headers

On the HTML page

Using @html.antiforgerytoken () in 1.html, and then using name in jquery, gets the value of the hidden field value and assigns it to the AJAX headers

2.var headtoken=$ (' Input[name= "__requestverificationtoken"]). Val ();

In script

"Viewport"Content="Width=device-width"/> <title>Person</title> <script src="~/scripts/jquery-3.3.1.min.js"></script> <script src="~/scripts/jquery.validate.js"></script> <script src="~/scripts/jquery.validate.unobtrusive.js"></script>"Form1">
@* @Html. AntiForgeryToken () *@ <divclass="Form-horizontal"> <divclass="Form-group"> <div>Name:<input type="text"Name="name"Value=""Id="name"/>Password:<input type="text"Name=" Age"Value=""Id=" Age"/> </div> <divclass="col-md-offset-2 col-md-10"> <input type="Button"Id="Save"Value="Create" class="btn Btn-default"/> </div> </div> </div> </form> <script>$ (function () {//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/userinfo', Cache:false, Headers:headers, data: {Name: $ ("#name"). Val (), Age: $ ("#age"). Val ()}, Success:function (data) {alert (data)}, Error:function () {alert ("Error") } }); }) }); </script></body>

3. Custom Authorizeattribute Properties

It mainly examines

(1) Whether the requested cookie contains a antiforgery name of the contract

(2) Whether the request headers has a ["__requestverificationtoken"], and cannot be empty, the agreed antiforgery name of the cookie and the value in the headers match

 Public classAntiforgerytoken:authorizeattribute {/// <summary>        ///         /// </summary>        /// <param name= "Filtercontext" ></param>         Public Override voidonauthorization (AuthorizationContext filtercontext) {varRequest =filterContext.HttpContext.Request; if(Request. Isajaxrequest ()) {varAntiforgerycookie =request.                Cookies[antiforgeryconfig.cookiename]; varCookievalue = Antiforgerycookie! =NULL? Antiforgerycookie.value:NULL; varHeadervalue = Request. headers["__requestverificationtoken"]; //gets the value in the head if it's empty, you don't go down.                if(string. IsNullOrEmpty (Headervalue)) {Base.                    Onauthorization (Filtercontext); return; }                //verification of anti-counterfeiting marks from cookies and Headersantiforgery.validate (Cookievalue,headervalue); }        }    }

ASP. NET MVC Ajax forgery request

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.