The anti-forgery token could not be decrypted

前端 未结 11 1200
萌比男神i
萌比男神i 2020-11-28 08:34

I have a form:

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

and a

相关标签:
11条回答
  • 2020-11-28 08:49

    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();
         }
      }
      
    0 讨论(0)
  • 2020-11-28 08:51

    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
    
    0 讨论(0)
  • 2020-11-28 08:55

    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.

    0 讨论(0)
  • 2020-11-28 09:01

    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.

    0 讨论(0)
  • 2020-11-28 09:02

    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

    0 讨论(0)
  • 2020-11-28 09:03

    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.

    0 讨论(0)
提交回复
热议问题