Search code examples
asp.net-mvc-4antiforgerytoken

MVC4 AntiForgery token cookie name is appended with random string


I am encountering an issue with MVC4's

@Html.AntiForgeryToken()

html helper. On my development machine, when I run the project, upon inspecting the headers (using Fiddler) , the name of the token returned is

__RequestVerificationToken

But when deployed to an IIS version 7.5 (Windows 2008 R2), then token name looks like:

__RequestVerificationToken_L2V6b3JkZXI1

Where is this getting changed? Is it because my application is not deployed to the "root folder" of the IIS? E.g. my application is deployed to

"http://myserver/myapp" instead of "http://myserver"

Solution

  • I found the answer after looking at the source code:

    http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.WebPages/Helpers/AntiForgeryConfig.cs
    

    Yes, because my application was deployed to a path, the following code below appends the encoded equivalent of the path... Hope this finding will save you trouble.

            // If the app path is provided, we're generating a cookie name rather than a field name, and the cookie names should
        // be unique so that a development server cookie and an IIS cookie - both running on localhost - don't stomp on
        // each other.
        internal static string GetAntiForgeryCookieName(string appPath)
        {
            if (String.IsNullOrEmpty(appPath) || appPath == "/")
            {
                return AntiForgeryTokenFieldName;
            }
            else
            {
                return AntiForgeryTokenFieldName + "_" + HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(appPath));
            }
        }