python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Preventing Cross-Site Request Forgery (CSRF) Attacks

MVC 5 Web API 2 Token Based Authentication

MVC 5 Preventing Cross-Site Request Forgery(CSRF) Attacks

Table of Contents

1. In the 1st step add the function GetTokenHeader() to get token header.
2. In second step add the script code for post the ajax request with token header for API controller.
3. Add the ValidateAntiForgeryToken attribute for validate the antiforgery token on controller actions.
4. validate the all request using RequestVerificationToken and HttpRequestMessage.

                   The below video show the steps where put the codes

For more details seen the below example.

//Step 1
//Put the code in cshtml page
    Models.UserSession userSession = (Models.UserSession)Session["userSession"];     
        public string GetTokenHeader()
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;               
//Step 2 //This is script code put in cshtml page

//Step 3 //This is controller code.
public IHttpActionResult GetByCTID(HttpRequestMessage RequestMsg)
            var re = Request;
            var headers = re.Headers;
            int CompanyID = 0, TenantID = 0, CostCenterID = 0;
            //This methods is used for Validate Request Header.
            if (headers.Contains("CompanyID"))
                CompanyID = Convert.ToInt32(headers.GetValues("CompanyID").First());
            if (headers.Contains("TenantID"))
                TenantID = Convert.ToInt32(headers.GetValues("TenantID").First());
            if (headers.Contains("CostCenterID"))
                CostCenterID = Convert.ToInt32(headers.GetValues("CostCenterID").First());
            ICollection pricing = mapper.MapDALPricings2BAL(objDalPricing.getAllPricingForConnect(CompanyID, TenantID, "N", CostCenterID));
            if (pricing == null)
                return NotFound();
            return Ok(pricing);

//Step 4
// This method is used to validate header requests for each call.
void ValidateAllHeaderRequest(HttpRequestMessage request)
                string cookieToken = string.Empty;
                string formToken = string.Empty;
                IEnumerable myTokenHeaders;
                bool tokenValue = request.Headers.TryGetValues("RequestVerificationToken",out myTokenHeaders);
                if (tokenValue)
                    string[] tokens = myTokenHeaders.First().Split(':');
                    var myTokensLength = tokens.Length;
                    if (myTokensLength == 2)
                        cookieToken = tokens[0].Trim();
                        formToken = tokens[1].Trim();
                AntiForgery.Validate(cookieToken, formToken);
            catch (System.Web.Mvc.HttpAntiForgeryException ex)
                throw new System.Web.Mvc.HttpAntiForgeryException("Anti forgery token cookie not found");


Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions