71
votes

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.

12
AutoGenerate will not create the same key on all machines. I'm confused why you said it can't be used, then you tried to use it.Erik Philips
and specify it (the encryption key) specifically - can please show exampleuser3331122
Wouldn't "AutoGenerate" generate a new key when your application pool reloads, causing this issue when a form from an older w3wp.exe is handled by a newer w3wp.exe?sisve
I got this error When i am Open Login Window Long Time, Then Try to Login Got this error. Just Reload this Login Window and Try to Login will Solve the Problem. But I Don't Know How to FIxHackbal Teamz

12 Answers

133
votes

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.

33
votes

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

17
votes

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.

17
votes

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.

6
votes

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();
       }
    }
    
3
votes

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.

3
votes

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
2
votes

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();
    ....
}
2
votes

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

1
votes

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.

1
votes

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...

0
votes

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

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