我正在尝试使用Microsoft .Net ViewStateUserKey和Double Submit Cookie实施跨站点请求伪造(CSRF)。有关更多信息,请访问此link
上面的代码在C#中,我将其转换为VB.Net。现在的问题是,这段代码中有一行
Page.PreLoad += master_Page_PreLoad;
当我尝试在VB.Net中转换同一行时,找不到任何此类事件Page.PreLoad
请帮助我该怎么做。
谢谢
答案 0 :(得分:0)
转换为VB的C#MasterPage模板如下:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
我相信您要查找的特定行是AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
。
作为将来的参考,如果您希望将C#代码转换为VB,反之亦然,则有一个非常出色的Telerik工具可以在此处找到:http://converter.telerik.com/。为了获得上面发布的代码,我只是在那儿运行了C#模板。
答案 1 :(得分:0)
您可以直接创建方法,
if (!token) {
navigate.push(routes.login)
return <Text>Redirect</Text>
}
无需解决此问题
Private Sub Page_PreRender(ByVal sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of " & "Anti-XSRF token failed.")
End If
End If
End Sub