Skip to content

Instantly share code, notes, and snippets.

@lorddev
Last active May 23, 2024 17:59
Show Gist options
  • Save lorddev/6f61ad57864ed5268cef to your computer and use it in GitHub Desktop.
Save lorddev/6f61ad57864ed5268cef to your computer and use it in GitHub Desktop.
Classic ASP version of ASP.NET MVC AntiForgeryToken validator
<%
' 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()
GetCookie = Request.Cookies("RequestVerificationToken")
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>
@Jswink1
Copy link

Jswink1 commented May 23, 2024

In order to get this to work i had to call "#include virtual ="/App/AntiForgeryTokenValidator.asp"" at the top of the page. "include file" did not work for me.

also, to call "vv.SetCookie", i had to wrap it in an IF statement and check if the page is not a post. Or else the cookie in the users session would just refresh to something different that what was saved in the form. Like so:

If Request.ServerVariables("REQUEST_METHOD") <> "POST" Then
vv.SetCookie
End If

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment