Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An exception was thrown while deserializing the token.The antiforgery token could not be decrypted in .Net Core 2.2 application

I am getting the error in my log. I spent most of my day finding the solution but could not find the one which meets my requirement.

Here is the log error

severity=[ERROR], ipaddress=xxxx, subprocess=Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery, description=An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {xxxxxxxxxx} was not found in the key ring. at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)

    "Certificates": {
    "StoreName": "My",
    "StoreLocation": "LocalMachine"
    "SerialNumber": "xxxxxxxxxxxx"
},
   
   private X509Certificate2 LCertificate()
    {
        var storeName = Configuration["Certificates:StoreName"];
        var storeLocation = Configuration["Certificates:StoreLocation"];
        string serialNumber = Configuration["Certificates: SerialNumber"];
        using(X509Store store = new X509Store(storeName,storeLocation))
        {
            var certificates = store.Certificates
                                    .Find(X509FindType.FindBySerialNumber,
                                          serialNumber,
                                          acceptValidCertOnly);             

            return certificates[0];
        }
    }
    
     public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentityServer
                .AddSigningCredential(new X509Certificate2(LCertificate()))
      
    }

   [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginModel model)
    {
like image 721
KeentoLearn Avatar asked Aug 17 '20 03:08

KeentoLearn


People also ask

What is the Antiforgery token could not be decrypted?

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.

How is Antiforgery token generated?

AntiForgeryToken() basically generate encrypted value based on the cookie and form data. So if you declare and use this @Html. AntiForgeryToken() for each than it will generate two different _RequestValidationToken. Better declare one global @token variable with @Html.

Why can't my tokens be decrypted?

If the tokens can't be decrypted then either one of two things is happening: Your encryption keys aren't being persisted across app restarts and the client is sending you a token from the prior instance of your app. You should get warnings about this in your logs when the application starts.

Can the antiforgery token be decrypted?

Random: The antiforgery token could not be decrypted. · Issue #3540 · dotnet/aspnetcore · GitHub Have a question about this project?

Where does validateantiforgerytoken store the encryption key?

The bad news (for running the app on Google App Engine) is that the code behind ValidateAntiForgeryToken uses encryption, and by default it stores encryption keys on the local web server. When I had only one web server running on my desktop, it worked beautifully.

Why is my antiforgery key not valid after restarting IIs?

Reason for this is that a restart causes a new keyring to load into memory, and the antiforgery key inside the form no longer validate. The latter case can be fixed in IIS by checking "load user profile" in app pool. . In my case I am using both single IIS server and multiple servers.


1 Answers

If

  • your app is hosted on multiple servers
  • has not configured shared data protection
  • you are not using sticky sessions

this will happen when user requests a page with a form from server A, and later submits the form to server B.

It may also happen on a single IIS server if

  • user requests a page with a form
  • you restart the server
  • user submits the form

Reason for this is that a restart causes a new keyring to load into memory, and the antiforgery key inside the form no longer validate.

The latter case can be fixed in IIS by checking "load user profile" in app pool.

More info: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.1

like image 107
Roar S. Avatar answered Oct 10 '22 20:10

Roar S.