我创建了一个ASP.Net Web窗体应用程序使用Visual Studio 2013,我正在使用.NET框架4.5.我想确保我的网站不受跨网站请求伪造(CSRF)的影响,我发现很多文章都在讨论如何在MVC应用程序上实现这一功能,但很少有文章讨论Web表单.在this StackOverflow question条 comments 中,有一条 comments 说

"这是一个老问题,但最新的Visual Studio 2012 ASP.NET

我的母版页不包含该答案中提到的代码.它真的包含在新的应用程序中吗?如果没有,添加它的最佳方式是什么?

推荐答案

ViewStateUserKey双重提交Cookie(&A)

从Visual Studio 2012开始,微软在新的web表单应用程序项目中添加了内置的CSRF保护.要使用此代码,请添加一个新的ASP.NET Web窗体应用程序添加到您的解决方案并查看网站.主代码隐藏在页面后面.此解决方案将对从网站继承的所有内容页应用CSRF保护.母版页.

要使此解决方案发挥作用,必须满足以下要求:

所有修改数据的web表单都必须使用该网站.母版页.

public partial class SiteMaster : MasterPage
{
  private const string AntiXsrfTokenKey = "__AntiXsrfToken";
  private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
  private string _antiXsrfTokenValue;

  protected void Page_Init(object sender, EventArgs e)
  {
    //First, check for the existence of the Anti-XSS cookie
    var requestCookie = Request.Cookies[AntiXsrfTokenKey];
    Guid requestCookieGuidValue;

    //If the CSRF cookie is found, parse the token from the cookie.
    //Then, set the global page variable and view state user
    //key. The global variable will be used to validate that it matches 
    //in the view state form field in the Page.PreLoad method.
    if (requestCookie != null
        && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
    {
      //Set the global token variable so the cookie value can be
      //validated against the value in the view state form field in
      //the Page.PreLoad method.
      _antiXsrfTokenValue = requestCookie.Value;

      //Set the view state user key, which will be validated by the
      //framework during each request
      Page.ViewStateUserKey = _antiXsrfTokenValue;
    }
    //If the CSRF cookie is not found, then this is a new session.
    else
    {
      //Generate a new Anti-XSRF token
      _antiXsrfTokenValue = Guid.NewGuid().ToString("N");

      //Set the view state user key, which will be validated by the
      //framework during each request
      Page.ViewStateUserKey = _antiXsrfTokenValue;

      //Create the non-persistent CSRF cookie
      var responseCookie = new HttpCookie(AntiXsrfTokenKey)
      {
        //Set the HttpOnly property to prevent the cookie from
        //being accessed by client side script
        HttpOnly = true,

        //Add the Anti-XSRF token to the cookie value
        Value = _antiXsrfTokenValue
      };

      //If we are using SSL, the cookie should be set to secure to
      //prevent it from being sent over HTTP connections
      if (FormsAuthentication.RequireSSL &&
          Request.IsSecureConnection)
      {
        responseCookie.Secure = true;
      }

      //Add the CSRF cookie to the response
      Response.Cookies.Set(responseCookie);
    }

    Page.PreLoad += master_Page_PreLoad;
  }

  protected void master_Page_PreLoad(object sender, EventArgs e)
  {
    //During the initial page load, add the Anti-XSRF token and user
    //name to the ViewState
    if (!IsPostBack)
    {
      //Set Anti-XSRF token
      ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;

      //If a user name is assigned, set the user name
      ViewState[AntiXsrfUserNameKey] =
             Context.User.Identity.Name ?? String.Empty;
    }
    //During all subsequent post backs to the page, the token value from
    //the cookie should be validated against the token in the view state
    //form field. Additionally user name should be compared to the
    //authenticated users name
    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.");
      }
    }
  }
}

Source

Asp.net相关问答推荐

IISExpress未在ARM64 Mac/.NET 4.8上启动

Asp.Net Core 创建一个控制器来使用 SendGrid 发送邮箱

IIS HTTP 错误 500.19

使用进程外会话状态的 ASP.NET 应用程序中的 SQL Server 连接问题

如何在页面加载之前运行 JavaScript 代码?

iframe.readyState 在 chrome 中不起作用

WebAPI 请求流支持

如何使用 javascript 获取 MVC 应用程序的基本 URL

IIS 6/ASP.NET Windows 身份验证 list ?

跨子域共享 ASP.NET cookie

使用 Elmah 处理 Web 服务中的异常

无法确定条件表达式的类型,因为 'string' 和 'System.DBNull' 之间没有隐式转换

如何在 IIS 7.5 上使用 ASP.NET 表单身份验证保护静态文件?

Page.IsValid 是如何工作的?

用于验证的数据注释,至少一个必填字段?

如何在 ASP.NET 站点中添加 favicon.ico

MVC 4 - Razor - 将变量传递到 href url

如何在 ASP.NET MVC 中设置时区?

为什么混合 Razor Pages 和 VueJs 是一件坏事?

MVC4 中 Global.asax.cs 页面中的问题