As part of my research for an upcoming project, I am working on a testbed application which has performs anti-XCRF validation.
While starting my research, I found this article, detailing how to do very nearly exactly what I am trying to do.
However, I hit a snag. I implemented the following bits of code, but every time I run my test action, a delete that has the [AntiForgeryValidate] attribute, I keep getting a HttpAntiForgeryException; what's more, in the request headers, there is no __RequestVerificationToken, even though as you can see from my code, I'm taking steps specifically to add it.
Request Verification Token Directive:
app.directive('requestVerificationToken', [
'$http',
function ($http) {
return function (scope, element, attrs) {
$http.defaults.headers.common['__RequestVerificationToken'] = attrs.requestVerificationToken || "no request verification token";
};
}
]);
AntiForgeryExtension.cs:
public static class AntiForgeryExtension
{
public static string RequestVerificationToken(this HtmlHelper helper)
{
// This name is dictated by the name of our validation token directive.
// See App/Common/requestVerificationTokenDir.js.
return String.Format("request-verification-token={0}", GetTokenHeaderValue());
}
private static string GetTokenHeaderValue()
{
string cookieToken;
string formToken;
System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
AntiForgeryValidate.cs:
public class AntiForgeryValidate : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (actionContext.Request.Headers.TryGetValues("__RequestVerificationToken", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
System.Web.Helpers.AntiForgery.Validate(cookieToken, formToken);
base.OnActionExecuting(actionContext);
}
}
TestController.cs:
public class HomeController : ApiController
{
//api/home/DeleteThingy
[HttpGet]
[AntiForgeryValidate]
public HttpResponseMessage DeleteThingy(int thingyId)
{
// ...Magic!
return Request.CreateResponse(HttpStatusCode.OK);
}
}
...and finally, Index.cshtml:
<div class='container'>
<input type='hidden' @Html.RequestVerificationToken() />
<div data-ng-view></div>
</div>
Question: What am I doing wrong, that is causing the __RequestVerificationToken to not appear in the headers that are passed back to the server when I hit a delete button on my front end?