I’m in the process of adding some UI functionality to a hybrid WebForms/MVC site. In this case, I’m adding some AJAX UI features to a WebForms page (via jQuery), and the data is coming from an MVC JsonResult. Everything is working 100%, with one exception:
I would like to implement the XSRF protection of AntiForgeryToken. I have used it in combination with the ValidateAntiForgeryToken attribute on my pure MVC applications, but would like to know how to implement the Html.AntiForgeryToken() method in WebForms. Here’s an example using a UrlHelper.
I’m having some trouble getting ViewContext / RequestContext “mocked” up correctly. How should I go about using HtmlHelpers within a WebForms page?
Edit:
I’m looking to retrieve the AntiForgeryToken from my WebForms page, not from the MVC JsonResult.
The key method is in the MVC source code:
GetAntiForgeryTokenAndSetCookieThis creates an instance of an internal sealed class called
AntiForgeryData.The instance is serialised into a cookie “__RequestVerificationToken_” + a base 64 encoded version of the application path.
The same instance of
AntiForgeryDatais serialised into a hidden input.The unique part of the
AntiForgeryDatais got with anRNGCryptoServiceProvider.GetBytes()All of this could be spoofed in a WebForms page, the only messy bit is the serialisation of the hidden sealed class. Unfortunately the key method (
GetAntiForgeryTokenAndSetCookie) relies onViewContext.HttpContext.Requestto get at the cookies, while the WebForm needs to useHttpContext.Current.Requestinstead.Update
Not much testing and a lot of code, but I think I’ve cracked this with a little reflection. Where I’ve used reflection I’ve left the equivalent line commented out above:
Usage is then similar to MVC:
It creates the same cookie and the same HTML as the MVC methods.
I haven’t bothered with the salt and domain methods, but they would be fairly easy to add in.