View Single Post
  #1 (permalink)  
Old October 10th, 2012, 02:50 PM
nthoeming nthoeming is offline
Registered User
Points: 58, Level: 1
Points: 58, Level: 1 Points: 58, Level: 1 Points: 58, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Jul 2012
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default AntiCSRF in VB? - Chapter 4

I'm attempting to reproduce the AntiCSRF class from Chapter 4 in VB and my skill level is less than stellar.

In particular, I'm running into issues adding the
page.PreRender += PagePreRender;
line from the PreRequestHandlerExecute method.

Does this module exist in VB anywhere?
If not, can you push me in the right direction?

My work-in-progress code:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Globalization

Public Class AntiCSRF
    Implements IHttpModule

#Region "IHttpModule Members"
    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

    End Sub

    Public Sub Init(context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
        AddHandler context.PreSendRequestHeaders, AddressOf AntiCSRF.PreSendRequestHeaders
        AddHandler context.PreRequestHandlerExecute, AddressOf AntiCSRF.PreRequestHandlerExecute
    End Sub
#End Region
    Private Shared Sub PreSendRequestHeaders(ByVal source As Object, ByVal args As EventArgs)
    End Sub
    Private Shared Sub PreRequestHandlerExecute(ByVal source As Object, ByVal args As EventArgs)
        Dim application As HttpApplication = CType(source, HttpApplication)
        Dim context As HttpContext = application.Context
        If (Not (context.Handler) Is Nothing) Then
            Dim page As Page = context.Handler
            If (Not (page) Is Nothing) Then

            End If
        End If
    End Sub
    Private Shared Sub PagePreRender(ByVal source As Object, ByVal eventArgs As EventArgs)
        Dim page As Page = CType(source, Page)
        If ((Not (page) Is Nothing) _
                    AndAlso (Not (page.Form) Is Nothing)) Then
            Dim csrfToken As String
            Dim context As HttpContext = HttpContext.Current
            If ((context.Request Is Nothing) _
                        OrElse ((context.Request.Cookies Is Nothing) _
                        OrElse ((context.Request.Cookies("__CSRFCOOKIE") Is Nothing) _
                        OrElse String.IsNullOrEmpty(context.Request.Cookies("__CSRFCOOKIE").Value)))) Then
                csrfToken = Guid.NewGuid.ToString("D", CultureInfo.InvariantCulture)
                csrfToken = page.Request.Cookies("__CSRFCOOKIE").Value
            End If
            Dim stateFormatter As ObjectStateFormatter = New ObjectStateFormatter
            page.ClientScript.RegisterHiddenField("__CSRFTOKEN", stateFormatter.Serialize(csrfToken))
        End If
    End Sub
End Class