The anti-forgery token could not be decrypted

115,222

Solution 1

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

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

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

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

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();
       }
    }
    
Share:
115,222
user3331122
Author by

user3331122

Updated on July 05, 2022

Comments

  • user3331122
    user3331122 almost 2 years

    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.

  • user3331122
    user3331122 about 10 years
    and specify it (the encryption key) specifically - can please show example. like validationKey="sdasdf34234defsdf+*-" decryptionKey="sdasdf34234defsdf+*-" and its key will be for all my users?
  • Domin8urMind
    Domin8urMind about 10 years
    Yes, this is how requests are validated in webfarm scenarios. HTH
  • John Shedletsky
    John Shedletsky almost 9 years
    How can I tell if this is happening to me, and how do I fix it?
  • John Shedletsky
    John Shedletsky almost 9 years
    By commenting out the AntiForgery token in my partial view, I stopped getting the error. The problem is now if that partial view is used on several different pages, I don't know when to apply the AntiForgery token.
  • Steve Dowling
    Steve Dowling almost 9 years
    Can't you just apply the token when you initialise each form or is your solution more complex than that?
  • Quinton Smith
    Quinton Smith almost 8 years
    I was also getting this error due to more than one anti-forgery token on the page (Log Off is wrapped by form element in MVC default template) but, I was doing ajax postback. Then I realised I was calling $('form').serialize() and changed that to $('#my-form-id').serialize().
  • sab669
    sab669 over 7 years
    I know this was over a year ago, but do you recall if this was immediately obvious @SteveDowling? Today, we've been getting a tremendous amount of calls from clients reporting this "key cannot be decrypted" error. We believe it's because of multiple calls to @Html.AntiforgeryToken() from different partials, but it's weird that it hasn't been an issue for months and then suddenly we're getting bombarded with complaints...
  • Steve Dowling
    Steve Dowling over 7 years
    I haven't touched this for ages but, from memory, I don't think it was obvious at all. It took a bit a of hacking to figure out what was going on.
  • Tony
    Tony about 7 years
    I know M$ gives the code to generate the keys.. but that link just makes life much easier. Thanks for giving location and a quick way to fix this. If mark this as the answer if it was my question :P
  • Paul F
    Paul F about 7 years
    Can someone clarify this for me please? One of the sites I've developed has this issue, and I'm going to try and track down the rogue AntiForgeryToken, but I'm not sure if the issue is with one form containing two tokens, or one page containing two tokens. Which is it?
  • Steve Dowling
    Steve Dowling about 7 years
    I think it is fine for the page to have two tokens as long as only one is being passed to the form. Check the generated HTML source and make sure each form on the page only has one hidden field containing an anti-forgery token. Search for __RequestVerificationToken in the generated page source.
  • Paul F
    Paul F about 7 years
    I checked all the forms on the page yesterday and couldn't find any issues - each one had only a single token. When I came in today and checked again, both instances of the site which were displaying this error are working correctly. Is it possible IIS or some worker processes had somehow screwed up? Literally nothing has changed in the code overnight.
  • Wouter Vanherck
    Wouter Vanherck about 5 years
    Worked out for me, even in production
  • ganders
    ganders over 4 years
    I believe this is happening to me. I deploy often, and even during high-traffic times, and it seems this only occurs on app restarts/deployments.
  • user2081126
    user2081126 about 4 years
    Having machine id will make things complicated when we move on to new servers. When we move on to new servers, someone should consciously update the web.config file is there another option that we can try
  • user2081126
    user2081126 about 4 years
    Having machine id will make things complicated when we move on to new servers. When we move on to new servers, someone should consciously update the web.config file is there another option that we can try
  • Biju Kalanjoor
    Biju Kalanjoor about 3 years
    It Helped me a lot.
  • Hassan Faghihi
    Hassan Faghihi almost 3 years
    thats what i want to do :D I have master page, and antiforgery in master, is always out side of page, and so out side of form. and the antiforgery in page? we need to repeat it a lot, and again it may not be inside the form which lay inside your master.
  • nkalfov
    nkalfov over 2 years
    would the keys be autodeleted when their lifetime expires?