locked
Anti-CSRF Tokens in ASP.NET Web-Forms Applicaiton RRS feed

  • Question

  • User-924931093 posted

    I have used this code in order to prevent CSRF attacks in our load-balanced site, but recently I started having [ViewState Verification Failed Exception].

    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;
    
    
     protected void Page_Init(object sender, EventArgs e)
            {
                if (Session["CurrentUser"] == null)
                {
                    Response.Redirect("/");
                }
    
    
                //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,
                        Expires = DateTime.Now.AddMinutes(10.0)
                    };
                    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)
            {
                try
                {
                    if (!IsPostBack)
                    {
                        // Set Anti-XSRF token
                        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                        ViewState[AntiXsrfUserNameKey] =  Session.SessionID ?? string.Empty;
                    }
                    else
                    {
    
                        // Validate the Anti-XSRF token
                        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                            || (string)ViewState[AntiXsrfUserNameKey] != (Session.SessionID ?? string.Empty))
                        {
    
                            Response.Redirect("/Error", false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SmtpMailer.SendMsg(ex.Message + ex.Source + ex.StackTrace, "Error on Prod");
                }
            }

    After giving up looking for a fix for it, So decided to look for another way to prevent CSRF/XSRF attacks, or at least not using ViewState keys in the code.

    So, my question is: is there another way/suggestion to replace what I have used in terms to prevent CSRF in the Master.cs file?

    Thanks in advance.

    Tuesday, March 12, 2019 7:44 PM

Answers

All replies

  • User475983607 posted

    So, my question is: is there another way/suggestion to prevent what I have used?

    Why not use a form input and a cookie?  This sounds like a like a good candidate for a UserControl placed in the master page form.

    Tuesday, March 12, 2019 8:03 PM
  • User-924931093 posted

    Sorry I didn't get what you mean, or maybe my question is not clear enough, simply it was: is there any other way to prevent csrf attacks as a replacement of what I have done?

    Tuesday, March 12, 2019 8:15 PM
  • User475983607 posted

    Sorry I didn't get what you mean, or maybe my question is not clear enough, simply it was: is there any other way to prevent csrf attacks as a replacement of what I have done?

    I would, as stated above, use a standard form input and cookie.  Not ViewState.  I would also wrap the logic in a UserControl so the logic can be controlled.

    Tuesday, March 12, 2019 9:07 PM
  • User-924931093 posted

    I would, as stated above, use a standard form input and cookie.  Not ViewState.  I would also wrap the logic in a UserControl so the logic can be controlled.

    Thanks for your reply, but still didn't get it at all, do you some samples? or references that can explain more?

    Wednesday, March 13, 2019 1:46 PM
  • User-1174608757 posted

    Hi basel@Simboliq,

    According to your description, if you want to preventcross-site request forgery (csrf) attacks in asp.net web forms without using ViewState keys , you could try to add a hidden field and a cookie by your self.

    You could add in Webform front end

    <%= System.Web.Helpers.AntiForgery.GetHtml() %>

    Then in code behind , you could set as below:

    protected void Page_Load(object sender, EventArgs e)
    {
    if (IsPostBack)
     AntiForgery.Validate();
    }

    Here is the link, I hope it will help you.

    https://stackoverflow.com/questions/29939566/preventing-cross-site-request-forgery-csrf-attacks-in-asp-net-web-forms

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 14, 2019 5:27 AM
  • User-924931093 posted

    That was really helpful! It solved a problem that I've been looking for a solution for it for more than 3 months! Thanks again.

    Monday, March 18, 2019 1:57 PM