防止ASP.NET Web表单中的跨站点请求伪造(CSRF)攻击 [英] preventing cross-site request forgery (csrf) attacks in asp.net web forms

查看:744
本文介绍了防止ASP.NET Web表单中的跨站点请求伪造(CSRF)攻击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Visual Studio 2013创建了一个ASP.Net Web窗体应用程序,并且我正在使用.NET Framework 4.5.我想确保我的网站不受跨站请求伪造(CSRF)的影响,我发现有很多文章都在谈论如何在MVC应用程序上实现此功能,但是很少有文章谈论Web表单.在此StackOverflow问题中,有一条评论指出

I have created an ASP.Net Web Forms application using Visual Studio 2013 and I am using .NET Framework 4.5. I want to make sure my site is secure from Cross-Site Request Forgery (CSRF), I have found many articles talking about how this feature is implemented on MVC apps, but very few talking about Web Forms. On this StackOverflow question one comment states that

这是一个老问题,但是最新的Visual Studio 2012 ASP.NET Web表单模板包括烘焙到母版中的反CSRF代码 页.如果您没有模板,请使用以下代码 生成:..."

"This is an old question, but the latest Visual Studio 2012 ASP.NET template for web forms includes anti-CSRF code baked into the master page. If you don't have the templates, here's the code it generates:..."

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

My master page does not contain the code mentioned in that answer. Is it really included in new applications? If not, what is the best way to add it?

推荐答案

ViewStateUserKey&两次提交Cookie

ViewStateUserKey & Double Submit Cookie

从Visual Studio 2012开始,Microsoft向新的Web窗体应用程序项目中添加了内置CSRF保护.若要使用此代码,请向您的解决方案中添加一个新的ASP .NET Web窗体应用程序,然后在页面后面查看Site.Master代码.该解决方案将CSRF保护应用于从Site.Master页面继承的所有内容页面.

Starting with Visual Studio 2012, Microsoft added built-in CSRF protection to new web forms application projects. To utilize this code, add a new ASP .NET Web Forms Application to your solution and view the Site.Master code behind page. This solution will apply CSRF protection to all content pages that inherit from the Site.Master page.

此解决方案必须满足以下要求:

The following requirements must be met for this solution to work:

所有进行数据修改的Web表单都必须使用Site.Master页面. 所有进行数据修改的请求都必须使用ViewState. 该网站必须没有任何跨站点脚本(XSS)漏洞.有关详细信息,请参见如何使用Microsoft .Net Web保护库修复跨站点脚本(XSS).

All web forms making data modifications must use the Site.Master page. All requests making data modifications must use the ViewState. The web site must be free from all Cross-Site Scripting (XSS) vulnerabilities. See how to fix Cross-Site Scripting (XSS) using Microsoft .Net Web Protection Library for details.

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.");
      }
    }
  }
}

来源

这篇关于防止ASP.NET Web表单中的跨站点请求伪造(CSRF)攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆