Click here to Skip to main content
14,879,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to prevent cross site script attack & block data without getting saved to DB. I am generating CSRF Token initially with GUID and then if therein the request cookie we pass that value. Also data can be saved to Database. I am using Visual Studio 2017 and same has been hosted. The check is being done in the Page Init and Page Pre Load Events.

What I have tried:

Below is my code:
#region Code for adding anti-csrf token

  private const string AntiXsrfTokenKey = "__AntiXsrfToken";
  private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
  private string _antiXsrfTokenValue;

  protected void Page_Init(object sender, EventArgs e)
  {
      try
      {
          Common.WriteDDSLog("Entered Master Page Init");
          NeSTBLL.Common.ChangeStyle(Page);
          if (!IsPostBack)
          {
              Session["CSRF"] = null;
          }
          else
          {

              if (Request.UrlReferrer == null)
              {
                  //throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                  Response.Redirect("~/CustomErrorPage.aspx", false);
              }

          }
          // The code below helps to protect against XSRF attacks
          var requestCookie = Request.Cookies[AntiXsrfTokenKey];
          Guid requestCookieGuidValue;
          if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
          {
              // Use the Anti-XSRF token from the cookie
              _antiXsrfTokenValue = requestCookie.Value;
              Common.WriteDDSLog("Anti XSRF Token Value 1" + _antiXsrfTokenValue);
              Page.ViewStateUserKey = _antiXsrfTokenValue;
              Common.WriteDDSLog("ViewState User Key 1" + Page.ViewStateUserKey);
          }
          else
          {
              // Generate a new Anti-XSRF token and save to the cookie
              _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
              Common.WriteDDSLog("Anti XSRF Token Value 2" + _antiXsrfTokenValue);
              Page.ViewStateUserKey = _antiXsrfTokenValue;
              Common.WriteDDSLog("ViewState User Key 2" + Page.ViewStateUserKey);
              var responseCookie = new HttpCookie(AntiXsrfTokenKey)
              {
                  HttpOnly = true,
                  Value = _antiXsrfTokenValue
              };
              if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
              {
                  responseCookie.Secure = true;
              }
              Response.Cookies.Set(responseCookie);
          }

          Page.PreLoad += master_Page_PreLoad;

          //int AbsoluteURL = Request.UrlReferrer.PathAndQuery.ToString().Length;
          //int URL_REF = Request.UrlReferrer.ToString().Length;
          //string URLREF = Request.UrlReferrer.ToString().Substring(0, URL_REF - AbsoluteURL).ToString();

          //Common.WriteDDSLog("Session URLREF : " + Session["URL_REF"].ToString());
          //Common.WriteDDSLog("URLREF1 : " + URLREF);
          //if (Session["URL_REF"].ToString() != URLREF)
          //{
          //    Response.Redirect("~/CustomError.aspx", false);
          //}
      }
      catch (Exception ex)
      {
          FormsAuthentication.SignOut();
          Session.Abandon();
          Session.Clear();
          Response.Clear();
          try
          {
              //Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
              //Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
              Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
              Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30); //Delete the cookie
          }
          catch { }


          HttpContext.Current.Response.Redirect("http://", true);
      }
      Common.WriteDDSLog("Completed Master Page Init");
  }

  protected void master_Page_PreLoad(object sender, EventArgs e)
  {
      try
      {

          Common.WriteDDSLog("Entered Master Page Pre Load");
          if (!IsPostBack)
          {
              // Set Anti-XSRF token
              ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
              Common.WriteDDSLog("ViewState Token Key" + ViewState[AntiXsrfTokenKey]);
              ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
              Common.WriteDDSLog("ViewState User Name Key" + ViewState[AntiXsrfUserNameKey]);
          }
          else
          {
              // Validate the Anti-XSRF token
              if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                  || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
              {

                  //throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                  Common.WriteDDSLog("Validation of Anti-XSRF token failed in Page Pre Load.");
                  Response.Redirect("~/CustomErrorPage.aspx", false);
              }
          }
      }
      catch (Exception ex)
      {
          FormsAuthentication.SignOut();
          Session.Abandon();
          Session.Clear();
          Response.Clear();
          try
          {
              //Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
              //Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
              Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
              Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30); //Delete the cookie
          }
          catch { }

          HttpContext.Current.Response.Redirect("http://", true);
      }
      Common.WriteDDSLog("Completed Master Page Pre Load");
  }
Posted
Updated 1-Jul-20 23:29pm
v3

1 solution

If you create a new Web Form Application project in VS 2013, site.master.cs will include the XSRF/CSRF code in the Page_Init section of the class. It looks like


C#
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;

 protected void Page_Init(object sender, EventArgs e)
    {
        // The code below helps to protect against XSRF attacks
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;
        if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            // Use the Anti-XSRF token from the cookie
            _antiXsrfTokenValue = requestCookie.Value;
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        else
        {
            // Generate a new Anti-XSRF token and save to the cookie
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                HttpOnly = true,
                Value = _antiXsrfTokenValue
            };
            if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            Response.Cookies.Set(responseCookie);
        }

        Page.PreLoad += master_Page_PreLoad;
    }

    protected void master_Page_PreLoad(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        else
        {
            // Validate the Anti-XSRF token
            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
            {
                throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
            }
        }
    }
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900