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"];     
    @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 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)
  {
            try
            {
                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");
            }
        }

ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book