MVC 5 Preventing Cross-Site Request Forgery(CSRF) Attacks
//Step 1
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.
//Put the code in cshtml page
@{ Models.UserSession userSession = (Models.UserSession)Session["userSession"]; @functions{ 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.
[ValidateAntiForgeryToken] [Route("API/Pricing/GetByCTID")] 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. ValidateAllHeaderRequest(RequestMsg); 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//Step 4pricing = mapper.MapDALPricings2BAL(objDalPricing.getAllPricingForConnect(CompanyID, TenantID, "N", CostCenterID)); if (pricing == null) { return NotFound(); } return Ok(pricing); }
// This method is used to validate header requests for each call.
void ValidateAllHeaderRequest(HttpRequestMessage request) { try { string cookieToken = string.Empty; string formToken = string.Empty; IEnumerablemyTokenHeaders; 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"); } }