Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 在WebForms中生成AntiForgeryToken_Asp.net Mvc_Xss - Fatal编程技术网

Asp.net mvc 在WebForms中生成AntiForgeryToken

Asp.net mvc 在WebForms中生成AntiForgeryToken,asp.net-mvc,xss,Asp.net Mvc,Xss,我有一个.NETWebForms站点,需要将其作为一个单独的应用程序发布到我的MVC应用程序中 Webform应用程序需要向MVC应用程序发布一些敏感值 是否有方法在我的WebForms应用程序中生成AntiForgeryToken(),以便它可以与表单post一起传递 否则,是否有人知道任何其他自定义防伪代码允许我执行类似于MVC的AntiForgeryValidation的操作。自己实现它并不太困难 生成GUID 把它放在一个隐藏的字段中 还将其置于会话或Cookie中(在后一种情况下,具

我有一个.NETWebForms站点,需要将其作为一个单独的应用程序发布到我的MVC应用程序中

Webform应用程序需要向MVC应用程序发布一些敏感值

是否有方法在我的WebForms应用程序中生成AntiForgeryToken(),以便它可以与表单post一起传递


否则,是否有人知道任何其他自定义防伪代码允许我执行类似于MVC的AntiForgeryValidation的操作。

自己实现它并不太困难

  • 生成GUID
  • 把它放在一个隐藏的字段中
  • 还将其置于会话或Cookie中(在后一种情况下,具有一些防篡改保护)
  • 在开始处理表单时,比较字段和存储的令牌

(如果你看一下MVC的实现,就没什么了。你只需要几个助手方法。)

WebForms在这方面也有类似的功能。通过(大多数选择),WebForms将验证ViewState1作为的一部分


1有这样的场景。主要是,它们归结为对GET请求(或在不检查IsPostback的情况下加载页面)或禁用ViewStateMAC进行危险操作。

您可以使用反射来获取用于设置cookie的MVC方法以及用于MVC验证的匹配表单输入。这样,您就可以拥有一个MVC操作,该操作具有
[AcceptVerbs(HttpVerbs.Post),ValidateAntiForgeryToken]
属性,您可以从WebForms生成的页面发布到这些属性


请参见此答案:

这是一个老问题,但最新的Visual Studio 2012 ASP.NET web表单模板在母版页中包含反CSRF代码。如果您没有模板,下面是它生成的代码:

Protected Sub Page_Init(sender As Object, e As System.EventArgs)


    ' The code below helps to protect against XSRF attacks
    Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey)
    Dim requestCookieGuidValue As Guid
    If ((Not requestCookie Is Nothing) AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue)) Then
        ' 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

        Dim responseCookie As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue}
        If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then
            responseCookie.Secure = True
        End If
        Response.Cookies.Set(responseCookie)
    End If

    AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub

Private Sub master_Page_PreLoad(sender As Object, e As System.EventArgs)


    If (Not IsPostBack) Then
        ' Set Anti-XSRF token
        ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
        ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
    Else
        ' Validate the Anti-XSRF token
        If (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _
            Or Not DirectCast(ViewState(AntiXsrfUserNameKey), String) = If(Context.User.Identity.Name, String.Empty)) Then
            Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
        End If
    End If
End Sub
Ian Ippolito的C版本回答如下:

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)
    {
        // The code below helps to 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
            };
            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)
    {
        if (!IsPostBack)
        {
            // Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        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.");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

非常好的帖子,但是你错过了3行,其中声明了
AntiXsrfTokenKey
AntiXsrfUserNameKey
,以及
\u antiXsrfTokenValue
。可能有助于更新:-)@IanIppolito此代码是否会验证直接指向处理程序的请求?因为当时我认为这段代码不会被执行。您好,先生,我正在使用VS2013和.Net FrameWork 4.5创建我的ASP.Net web表单应用程序,但我的母版页不包含这段自动生成的代码,我如何知道我的网站是否不受CSRF的影响?您能提供这段自动生成代码的C#版本吗?@ShekharPankaj请参阅。在集成之前确保您理解它(即它保护您免受什么影响,更重要的是)。@Richard您应该发布代码。我在cookie中需要什么防篡改保护?加密吗?我如何做到这一点?是否需要使用上下文中的用户标识进行验证?当上下文在页面之间切换时,视图状态将保持为该页面的状态。如果身份在验证运行时发生更改(通过使用多个选项卡浏览),则会引发异常,因为ViewState没有更改。
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)
    {
        // The code below helps to 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
            };
            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)
    {
        if (!IsPostBack)
        {
            // Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        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.");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}