Search code examples
c#asp.net-mvc-4antiforgerytoken

Using AntiForgeryToken between multiple ASP.NET sub projects


When I use @Html.AntiForgeryToken() in a form whose action is in the same project, it works perfectly. However, if the action place for the form is in a different project within the same solution, I get the following error:

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.

Is there a way to use AntiForgeryToken between different projects?


Solution

  • The signing/encryption of the anti-forgery tokens is governed by the keys held in the <machinekey> section of your web config. If this isn't set, then the value is auto-generated for each app. This means that each app will have a different machine key, so tokens from one app can't be decrypted by another.

    Fortunately, it is possible to generate your own values and store them in your web config for each app. The process for doing this is well described here:

    https://msdn.microsoft.com/en-us/library/ff649308.aspx#paght000007_webfarmdeploymentconsiderations

    If security isn't your top concern, then you might consider one of the many available online machinekey generators. As I couldn't find any secured with TLS/SSL/HTTPS and that we don't know the operators of these sites, I think trust is a big issue with these.