Advertisement
Guest User

Untitled

a guest
Oct 10th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
ASP 1.80 KB | None | 0 0
  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. {
  6.     // The code below helps to protect against XSRF attacks
  7.     var requestCookie = Request.Cookies[AntiXsrfTokenKey];
  8.     Guid requestCookieGuidValue;
  9.     if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
  10.     {
  11.        // Use the Anti-XSRF token from the cookie
  12.        _antiXsrfTokenValue = requestCookie.Value;
  13.        Page.ViewStateUserKey = _antiXsrfTokenValue;
  14.     }
  15.     else
  16.     {
  17.        // Generate a new Anti-XSRF token and save to the cookie
  18.        _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
  19.        Page.ViewStateUserKey = _antiXsrfTokenValue;
  20.        var responseCookie = new HttpCookie(AntiXsrfTokenKey)
  21.        {
  22.           HttpOnly = true,
  23.           Value = _antiXsrfTokenValue
  24.        };
  25.        if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
  26.        {
  27.           responseCookie.Secure = true;
  28.        }
  29.        Response.Cookies.Set(responseCookie);
  30.     }
  31.     Page.PreLoad += master_Page_PreLoad;
  32. }
  33. protected void master_Page_PreLoad(object sender, EventArgs e)
  34. {
  35.     if (!IsPostBack)
  36.     {
  37.        // Set Anti-XSRF token
  38.        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
  39.        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
  40.     }
  41.     else
  42.     {
  43.        // Validate the Anti-XSRF token
  44. if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue ||
  45.           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
  46.        {
  47.           throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
  48.        }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement