如何在ASP.net 3.5中实现Anti XSRF令牌

时间:2015-02-03 10:18:11

标签: c# asp.net .net csrf csrf-protection

我在框架工作3.5中添加了由VS 2012在.Net Web应用程序中生成的Anti Xsrf令牌代码,在应用程序中提交任何表单时出现错误:

  

System.Web.HttpException:viewstate MAC验证失败。如果此应用程序由Web场或群集托管,请确保配置指定相同的validationKey和验证算法。 AutoGenerate不能在群集中使用。 http://go.microsoft.com/fwlink/?LinkID=314055 ---> System.Web.UI.ViewStateException:无效的viewstate。客户IP:           Const AntiXsrfTokenKey As String =" __ AntiXsrfToken"       Const AntiXsrfUserNameKey As String =" __ AntiXsrfUserName"       Dim _antiXsrfTokenValue As String

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

我在网络配置中禁用了ViewstateMac页面,但我仍然遇到此错误,我知道禁用ViewStateMac在安全性方面不好。我的应用程序在生产中的Web场中托管,但不在本地环境中托管。

0 个答案:

没有答案