The anti-forgery token could not be decrypted

asp.net Mvcasp.net Mvc-4

asp.net Mvc Problem Overview


I have a form:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()...

and action:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl, string City)
{
}

occasionally (once a week), I get the 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 configuration > specifies explicit encryption and validation keys. AutoGenerate cannot > be used in a cluster.

i try add to webconfig:

<machineKey validationKey="AutoGenerate,IsolateApps"  
    decryptionKey="AutoGenerate,IsolateApps" />

but the error still appears occasionally

I noticed this error occurs, for example when a person came from one computer and then trying another computer

Or sometimes an auto value set with incorrect data type like bool to integer to the form field by any jQuery code please also check it.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

I just received this error as well and, in my case, it was caused by the anti-forgery token being applied twice in the same form. The second instance was coming from a partial view so wasn't immediately obvious.

Solution 2 - asp.net Mvc

validationKey="AutoGenerate"

This tells ASP.NET to generate a new encryption key for use in encrypting things like authentication tickets and antiforgery tokens every time the application starts up. If you received a request that used a different key (prior to a restart for instance) to encrypt items of the request (e.g. authenication cookies) that this exception can occur.

If you move away from "AutoGenerate" and specify it (the encryption key) specifically, requests that depend on that key to be decrypted correctly and validation will work from app restart to restart. For example:

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

You can read to your heart's content at MSDN page: How To: Configure MachineKey in ASP.NET

Solution 3 - asp.net Mvc

Just generate <machineKey .../> tag from a link for your framework version and insert into <system.web><system.web/> in Web.config if it does not exist.

Hope this helps.

Solution 4 - asp.net Mvc

If you get here from google for your own developer machine showing this error, try to clear cookies in the browser. Clear Browser cookies worked for me.

Solution 5 - asp.net Mvc

in asp.net Core you should set Data Protection system.I test in Asp.Net Core 2.1 or higher.

there are multi way to do this and you can find more information at Configure Data Protection and Replace the ASP.NET machineKey in ASP.NET Core and key storage providers.

  • first way: Local file (easy implementation)

    startup.cs content:

     public class Startup
     {
        public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            Configuration = configuration;
            WebHostEnvironment = webHostEnvironment;
        }
    
        public IConfiguration Configuration { get; }
        public IWebHostEnvironment WebHostEnvironment { get; }
    
        // This method gets called by the runtime.
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // .... Add your services like :
            // services.AddControllersWithViews();
            // services.AddRazorPages();
    
            // ----- finally Add this DataProtection -----
            var keysFolder = Path.Combine(WebHostEnvironment.ContentRootPath, "temp-keys");
            services.AddDataProtection()
                .SetApplicationName("Your_Project_Name")
                .PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
                .SetDefaultKeyLifetime(TimeSpan.FromDays(14));
        }
     }
    
  • second way: save to db

    The Microsoft.AspNetCore.DataProtection.EntityFrameworkCore NuGet package must be added to the project file

    Add MyKeysConnection ConnectionString to your projects ConnectionStrings in appsettings.json > ConnectionStrings > MyKeysConnection.

    Add MyKeysContext class to your project.

    MyKeysContext.cs content:

     public class MyKeysContext : DbContext, IDataProtectionKeyContext
     {
        // A recommended constructor overload when using EF Core 
        // with dependency injection.
        public MyKeysContext(DbContextOptions<MyKeysContext> options) 
            : base(options) { }
    
        // This maps to the table that stores keys.
        public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
     }
    

    startup.cs content:

     public class Startup
     {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime.
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // ----- Add this DataProtection -----
            // Add a DbContext to store your Database Keys
            services.AddDbContext<MyKeysContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MyKeysConnection")));
    
            // using Microsoft.AspNetCore.DataProtection;
            services.AddDataProtection()
                .PersistKeysToDbContext<MyKeysContext>();
            
            // .... Add your services like :
            // services.AddControllersWithViews();
            // services.AddRazorPages();
        }
     }
    

Solution 6 - asp.net Mvc

If you use Kubernetes and have more than one pod for your app this will most likely cause the request validation to fail because the pod that generates the RequestValidationToken is not necessarily the pod that will validate the token when POSTing back to your application. The fix should be to configure your nginx-controller or whatever ingress resource you are using and tell it to load balance so that each client uses one pod for all communication.

Update: I managed to fix it by adding the following annotations to my ingress:

https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/

Name	Description	Values
nginx.ingress.kubernetes.io/affinity	Sets the affinity type	string (in NGINX only cookie is possible
nginx.ingress.kubernetes.io/session-cookie-name	Name of the cookie that will be used	string (default to INGRESSCOOKIE)
nginx.ingress.kubernetes.io/session-cookie-hash	Type of hash that will be used in cookie value	sha1/md5/index

Solution 7 - asp.net Mvc

I ran into this issue in an area of code where I had a view calling a partial view, however, instead of returning a partial view, I was returning a view.

I changed:

return View(index);

to

return PartialView(index);

in my control and that fixed my problem.

Solution 8 - asp.net Mvc

I got this error on .NET Core 2.1. I fixed it by adding the Data Protection service in Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection();
    ....
}

Solution 9 - asp.net Mvc

you are calling more than one the @Html.AntiForgeryToken() in your view

Solution 10 - asp.net Mvc

I get this error when the page is old ('stale'). A refresh of the token via a page reload resolves my problem. There seems to be some timeout period.

Solution 11 - asp.net Mvc

I found a very interesting workaround for this problem, at least in my case. My view was dynamically loading partial views with forms in a div using ajax, all within another form. the master form submits no problem, and one of the partials works but the other doesn't. The ONLY difference between the partial views was at the end of the one that was working was an empty script tag

    <script type="text/javascript">
    </script> 

I removed it and sure enough I got the error. I added an empty script tag to the other partial view and dog gone it, it works! I know it's not the cleanest... but as far as speed and overhead goes...

Solution 12 - asp.net Mvc

My fix for this was to get the cookie and token values like this:

AntiForgery.GetTokens(null, out var cookieToken, out var formToken);

Solution 13 - asp.net Mvc

I know I'm a little late to the party, but I wanted to add another possible solution to this issue. I ran into the same problem on an MVC application I had. The code did not change for the better part of a year and all of the sudden we started receiving these kinds of error messages from the application.

We didn't have multiple instances of the anti-forgery token being applied to the view twice.

We had the machine key set at the global level to Autogenerate because of STIG requirements.

It was exasperating until I got part of the answer here: https://stackoverflow.com/a/2207535/195350:

> If your MachineKey is set to AutoGenerate, then your verification > tokens, etc won't survive an application restart - ASP.NET will > generate a new key when it starts up, and then won't be able to > decrypt the tokens correctly.

The issue was that the private memory limit of the application pool was being exceeded. This caused a recycle and, therefore, invalidated the keys for the tokens included in the form. Increasing the private memory limit for the application pool appears to have resolved the issue.

Solution 14 - asp.net Mvc

For those getting this error on Google AppEngine or Google Cloud Run, you'll need to configure your ASP.NET Core website's Data Protection.

The documentation from the Google team is easy to follow and works.

https://cloud.google.com/appengine/docs/flexible/dotnet/application-security#aspnet_core_data_protection_provider

A general overview from the Microsoft docs can be found here:

https://cloud.google.com/appengine/docs/flexible/dotnet/application-security#aspnet_core_data_protection_provider

Note that you may also find you're having to login over and over, and other quirky stuff going on. This is all because Google Cloud doesn't do sticky sessions like Azure does and you're actually hitting different instances with each request.

Other errors logged, include:

Identity.Application was not authenticated. Failure message: Unprotect ticket failed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3331122View Question on Stackoverflow
Solution 1 - asp.net MvcSteve DowlingView Answer on Stackoverflow
Solution 2 - asp.net MvcDomin8urMindView Answer on Stackoverflow
Solution 3 - asp.net Mvclogical8View Answer on Stackoverflow
Solution 4 - asp.net Mvcramons03View Answer on Stackoverflow
Solution 5 - asp.net MvcD.L.MANView Answer on Stackoverflow
Solution 6 - asp.net MvcPussInBootsView Answer on Stackoverflow
Solution 7 - asp.net Mvcarmstb01View Answer on Stackoverflow
Solution 8 - asp.net MvcCosminView Answer on Stackoverflow
Solution 9 - asp.net MvcHamid JolanyView Answer on Stackoverflow
Solution 10 - asp.net MvcbarrypickerView Answer on Stackoverflow
Solution 11 - asp.net MvcJosawalkView Answer on Stackoverflow
Solution 12 - asp.net MvcAlexanderView Answer on Stackoverflow
Solution 13 - asp.net MvcDerHaifischView Answer on Stackoverflow
Solution 14 - asp.net MvcLuke PuplettView Answer on Stackoverflow