Hi
I've followed the instructions in the book seemingly correctly, but my aspx page does not contain the hidden field after I have created a reference to the AntiCSRF class library
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Globalization;
namespace AntiCSRF
{
class AntiCSRF : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += new EventHandler(PreSendRequestHeaders);
context.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
#endregion
private static void PreSendRequestHeaders(object source, EventArgs args)
{
}
private static void PreRequestHandlerExecute(object source, EventArgs args)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
if (context.Handler != null)
{
Page page = context.Handler as Page;
if (page != null)
{
page.PreRender += PagePreRender;
}
}
}
private static void PagePreRender(object source, EventArgs args)
{
Page page = source as Page;
if (page != null && page.Form != null)
{
string csrfToken;
HttpContext context = HttpContext.Current;
if (context.Request == null ||
context.Request.Cookies == null ||
context.Request.Cookies["__CSRFCOOKIE"] == null ||
string.IsNullOrEmpty(context.Request.Cookies["__CSRFCOOKIE"].Value))
{
csrfToken = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
context.Items["Wrox.CSRFContext"] = csrfToken;
}
else
{
csrfToken = page.Request.Cookies["__CSRFCOOKIE"].Value;
ObjectStateFormatter stateFormatter = new ObjectStateFormatter();
page.ClientScript.RegisterHiddenField("__CSRFTOKEN",
stateFormatter.Serialize(csrfToken));
}
}
}
}
}
I am using Visual Studio 2008. My Web.config looks like
Code:
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="AntiCSRF" type="AntiCSRF.AntiCSRF, AntiCSRF"/>
</httpModules>
Any idea what I might be missing?
Cheers
Stewart