WebForms 应用程序中的 ValidateAntiForgeryToken

ValidateAntiForgeryToken in WebForms Application(WebForms 应用程序中的 ValidateAntiForgeryToken)

本文介绍了WebForms 应用程序中的 ValidateAntiForgeryToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些关于使用 ValidateAntiForgeryToken 来防止 XSRF/CSRF 攻击的文章.然而,我所看到的似乎只与 MVC 相关.

I have done some reading about the use of ValidateAntiForgeryToken to prevent XSRF/CSRF attacks. However what I have seen seems to relate only to MVC.

这些是我看过的文章:

ValidateAntiForgeryToken 用途、解释和示例

CSRF 和 AntiForgeryToken

ASP.NET MVC 和网页中的 XSRF/CSRF 预防

如何在 WebForms 应用程序中实现此功能或类似功能?

How can I implement this or something similar in a WebForms Application?

推荐答案

我发现这篇文章 How To Fix Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie 使用以下信息代码和说明:

I found this article How To Fix Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie with the following information code and instructions:

从 Visual Studio 2012 开始,Microsoft 向新的 Web 表单应用程序项目添加了内置 CSRF 保护.要利用此代码,请将新的 ASP .NET Web 窗体应用程序添加到您的解决方案并查看 Site.Master 代码隐藏页面.此解决方案将对继承自 Site.Master 页面的所有内容页面应用 CSRF 保护.

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:

•所有进行数据修改的网络表单都必须使用 Site.Master页面.

•All web forms making data modifications must use the Site.Master page.

•所有进行数据修改的请求都必须使用 ViewState.

•All requests making data modifications must use the ViewState.

•网站必须不受所有跨站脚本(XSS)的影响漏洞.请参阅如何修复跨站脚本 (XSS) 使用Microsoft .Net Web 保护库了解详情.

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

}

这篇关于WebForms 应用程序中的 ValidateAntiForgeryToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:WebForms 应用程序中的 ValidateAntiForgeryToken

基础教程推荐