2
Vote

Change to Antiforgery Token makes HtmlHelper.AntiForgeryToken less testable.

description

This
change in MVC4 RC broke one of our unit tests. In our application, we created an extension method for HtmlHelper which gerneates our sign out link. Our sign out link consists of a form post with a AntiForgeryToken. Our unit test validates that string
returned from the method matches an expected value. We had to search for, and remove the actual AntiForgery token value since it always changes, but the rest of the string is something we could validate. Here is a small code snippet that shows the use of html.AntiForgeryToken().


var form = string.Format(CultureInfo.InvariantCulture, format, html.AttributeEncode(url), html.AttributeEncode(linkText),html.AntiForgeryToken());
In MVC4 RC, the call to AntiForgeryToken(), now uses the parameterless version of AntiForgery.GetHtml(), which in turn throws an exception if HttpContext.Current is null.
We were able to work around this by setting HttpContext.Current to a new HttpContext in our setup method, instead of setting up the ViewContext.HttpContext which we were doing previously (with a fake based on
HttpContextBase). Thankfully we didn't need to setup or mock anything too specific for this test.

comments

marcind wrote Jun 8, 2012 at 7:04 PM

The description was copied over from http://aspnetwebstack.codeplex.com/discussions/358882.

We should address this by adding a AntiForgery.GetHtml() overload that accepts a HttpContextBase instance (should probably make it EditorBrowsable(Never)) and then have the MVC helper call into it passing in ViewContext.HttpContext.

rosieks wrote Jan 22 at 8:49 AM

I have similar issue with ValidateAntiForgeryTokenAttribute and invoking OnAuthorize.