tekguy
7/2/2014 - 4:00 PM

Anti Forgery token class for classic asp

Anti Forgery token class for classic asp

<%
' Use with a very short session (basically the page lifecycle, GET then POST)
Class AntiForgeryValidator
    
    Private m_securityToken
    
    
    Sub SetCookie()
        m_securityToken = CreateWindowsGuid()
        Response.Cookies("RequestVerificationToken") =  m_securityToken
        Response.Cookies("RequestVerificationToken").Secure = True
        Response.AddHeader "X-Frame-Options", "SAMEORIGIN"
    End Sub
    
    Function GetCookie()
        m_securityToken =   Request.Cookies("RequestVerificationToken")
        GetCookie =  m_securityToken
    End Function
    
    Function CreateWindowsGuid()
        CreateWindowsGuid = CreateGuid(8) & "-" & _
        CreateGuid(4) & "-" & _
        CreateGuid(4) & "-" & _
        CreateGuid(4) & "-" & _
        CreateGuid(12)
    End Function
    
    Function CreateGuid(length)
' VbScript keywords, Randomize is a sub, and Timer is a function.
        Randomize Timer
        Dim counter
        Dim guid
        Const Valid = "0123456789ABCDEF"
        For counter = 1 To length
            guid = guid & Mid(Valid, Int(Rnd(1) * Len(Valid)) + 1, 1)
        Next
        
        CreateGuid = guid
    End Function
    
    Function GetFormInputElement
        GetFormInputElement = "<input name=""RequestVerificationToken"" type=""hidden"" " &_
        " value=""" & m_securityToken & """ />"
        
    End Function
    
    Function Validate
        Dim formValue
        formValue = Request.Form("RequestVerificationToken")
        Dim cookieValue
        cookieValue = GetCookie()
        Response.Write "cookieValue = " & cookieValue & vbCrLf
        Response.Write "formValue = " & formValue & vbCrLf
        Validate = (cookieValue = formValue and Len(cookieValue) > 0)
        
    End Function
    
End Class

Dim vv
Set vv = new AntiForgeryValidator
'vv.SetCookie
Response.Write vv.GetCookie() & VbCrLf
Response.Write vv.GetFormInputElement() & vbCrLf

Response.Write vv.Validate() & vbCrLf
%>

<form action="AntiForgery.asp" method="POST">
    <%=vv.GetFormInputElement() %>
    <input type="submit" value="click" />



</form>