当前位置:  开发笔记 > 编程语言 > 正文

在WebForms中生成AntiForgeryToken

如何解决《在WebForms中生成AntiForgeryToken》经验,为你挑选了3个好方法。

我有一个.NET Webforms站点,感谢需要发布到我的MVC应用程序,该应用程序当前位于Webform站点内作为单独的应用程序.

Webform应用程序需要将一些敏感值POST到MVC应用程序.

有没有办法在我的WebForms应用程序中生成AntiForgeryToken(),以便它可以与表单发布一起传递.

否则,任何人都知道任何其他自定义防伪代码,这将允许我做类似于MVC的AntiForgeryValidation.



1> Ian Ippolito..:

这是一个老问题,但最新的Web表单Visual Studio 2012 ASP.NET模板包含烘焙到母版页的反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



2> Richard..:

自己实施并不太难.

生成GUID

把它放在一个隐藏的领域

也把它放在Session或Cookie中(在后一种情况下,带有一些防篡改保护)

在处理开始时,表单比较字段和存储的令牌.

(如果你看一下MVC的实现,它就没那么多了.你只需要一些辅助方法.)


@ShekharPankaj请参阅[OWASP .NET安全备忘单](https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet#ASP.NET_Web_Forms_Guidance).确保在集成之前了解它(即它保护您的内容,更重要的是[它不能保护您的内容](http://security.stackexchange.com/q/59470)).

3> DavidC..:

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)
    {

    }
}

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有