Akash Dani

Akash Dani

  • NA
  • 87
  • 23.5k

How to implement and Validate CSRF method in asp.net

Sep 6 2019 1:20 AM
I am using asp.net application and I dont know how to implement and validate CSRF tokens in asp.net.I want to validate these tokens in each request.
Can anyone help me?
And I have added this following code in Masterpage
  1. private const string AntiXsrfTokenKey = "__AntiXsrfToken";    
  2. private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";    
  3. private string _antiXsrfTokenValue;      
  4. protected void Page_Init(object sender, EventArgs e) {    
  5.  var requestCookie = Request.Cookies[AntiXsrfTokenKey];    
  6.  Guid requestCookieGuidValue;    
  7.  if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) {    
  8.   _antiXsrfTokenValue = requestCookie.Value;    
  9.   Page.ViewStateUserKey = _antiXsrfTokenValue;    
  10.     
  11.  } else {    
  12.   _antiXsrfTokenValue = Guid.NewGuid().ToString("N");    
  13.   Page.ViewStateUserKey = _antiXsrfTokenValue;    
  14.   var responseCookie = new HttpCookie(AntiXsrfTokenKey) {    
  15.    HttpOnly = true,    
  16.     Value = _antiXsrfTokenValue    
  17.   };    
  18.   if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) {    
  19.    responseCookie.Secure = true;    
  20.   }    
  21.   Response.Cookies.Set(responseCookie);    
  22.  }    
  23.     
  24.  Page.PreLoad += master_Page_PreLoad;    
  25. }    
  26.     
  27. protected void master_Page_PreLoad(object sender, EventArgs e) {    
  28.  try {    
  29.   if (!IsPostBack) {    
  30.    ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;    
  31.    ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ? ? String.Empty;    
  32.   } else {    
  33.    //Validate the Anti-XSRF token    
  34.    if ((string) ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string) ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ? ? String.Empty)) {    
  35.     throw new InvalidOperationException("Validation of " + "Anti-XSRF token failed.");    
  36.    }    
  37.   }    
  38.  } catch (Exception ex) {    
  39.   activityLog.Write("MasterPage->PageLoad->Exception->" + ex.Message.ToString());    
  40.   Session.Clear();    
  41.   Session.RemoveAll();    
  42.   Session.Abandon();    
  43.   Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);    
  44.   Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId"""));    
  45.   ScriptManager.RegisterStartupScript(this, GetType(), "DeleteCookie""DeleteCookie();"true);    
  46.   Response.Redirect("Default.aspx"false);    
  47.  }    
  48. } 

Answers (1)