Search code examples
c#cookiesasp.net-mvc-5antiforgerytoken

MVC 5 @Html.AntiForgeryToken() generating html tag with empty value


Title is pretty self-explanatory. The helper Razor tag is basically generating the token cookie the way it was supposed to, but not the correct hidden tag. Already checked the syntax, forms aren't using AJAX, and the cookie is apparently correct, so...

I'd rather take my chances of having this question marked as a duplicate than spending weeks on a needle in a haystack kind of issue.

View:

@model model
@{
    ViewBag.Title = "Title";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    //content
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ControllerName([Bind(Include = "fields")] Class objectClass)
{
    //content
}

Tag:

<input name="__RequestVerificationToken" type="hidden" value="">

Cookie:

name,value,domain,path,expires,httpOnly,secure
__RequestVerificationToken,5iRF4KpqPUPqnqRnlt74YrS99mOXW7Y-WcjKFOz3GmH3DmtuQPEHHAjm8vqZg9Z7P7F3rymZ2zojemQwJp0meq2etANdI5rm9n0RT7jjqCE1,localhost,/,Sessão,true,false

UPDATE 1:

Turns out it was happening because of jQuery. I was suspecting it to be due to incompatibility with the version that was installed, 3.1.1, the currently latest stable one. It has the following condition around lines 7958-7961 that were forcefully removing the element attribute:

// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
    this.value = val;
}

But in the end I found that the condition has been around ever since v1, so even with debugging the client code, it still remains a mistery why it happens exclusively in this project. Anyway, thanks for the feedback.


Solution

  • At first I was suspecting it was jQuery 3.1.1 that was causing it somehow, but what I hadn't noticed was that I had stopped using my Globalize.js bundle. Globalize looks like a great validation plugin based on its premise, but it has too many dependencies, which I didn't have then and to this day can't find all of them yet, even with checking every official channel they have I can find.

    Their own dependency guide site (take a look at the full build): https://johnnyreilly.github.io/globalize-so-what-cha-want/

    What was breaking/removing my hidden AntiForgeryToken input in the end was some sort of conflict when using jQuery.validate and Globalize at the same time. Could be because of missing dependencies, but I guess I'll never know since I haven't really seen so far a working system using both (Globalize with all features) at the same time.

    And I did look into the file ordering, jQuery.validateglobalize, all of that, btw. So long, Globalize.

    Hope this serves as reference to anyone in the future that may happen to stumble on the same issue.