aspnetcore: The antiforgery token could not be decrypted - Only for specific user

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

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 {669d513e-a172-4851-b160-04b523abbc1e} 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.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)


We insert an anti-forgery token into the form using @Html.AntiForgeryToken() and validate the request using the [ValidateAntiForgeryToken], however we occasionally get the error above when one user tries to submit.

How is the key generated? Why does the user affect the generation of the token?

Expected Behavior

When user submit a form, the request token is valid and the user request is accepted.

Steps To Reproduce

  1. Create a cshtml page
  2. Include an antiforgery token in the form using @Html.AntiForgeryToken()
  3. Annotate the controller method with [ValidateAntiForgeryToken]
  4. Make a post request with the token

Exceptions (if any)

An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.

.NET Version

netcoreapp3.1

Anything else?

We have tried this with different users, different devices and different browsers.

Only this user has the issue, and it is correlated with the logs’ timestamp.

I’ve checked the source code, and was wondering could it be due to special characters in the user name?

https://github.com/dotnet/aspnetcore/blob/main/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs No response

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 3
  • Comments: 45 (21 by maintainers)

Most upvoted comments

I have a case that is not user specific. I will report it here, as I am not fully certain that it is an issue or expected behaviour. It might help with this.

Context:

  • a blazor .NET 8 Web App. App & Routes configured for interactive server.
  • the entrypoint is anonymous, no auth cookie required.
  • the application is hosted on IIS, on a path (example: my.website.com/ThisIsTheBasePathOfTheApp)
    • The base path is configured with /ThisIsTheBasePathOfTheApp/.

Simply navigating to my.website.com/ThisIsTheBasePathOfTheApp works no problem. Now, if we navigate to it after we change the casing of a single letter, I get a familiar error exception. For example, if we go to my.website.com/thisIsTheBasePathOfTheApp (first t is lowercase).

Exception: The antiforgery token could not be decrypted.

Source: Microsoft.AspNetCore.Antiforgery StackTrace:

  • at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
  • at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)

InnerException: The key {597fc0e8-bbce-4963-b068-0f809a667142} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning

Source: Microsoft.AspNetCore.DataProtection StackTrace:

  • at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
  • at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
  • at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)

Edit:

I suppose this is more related with #5405, but I cannot be certain.

If you are running your app on a web farm or cloud environment, you should persist the data protection key, otherwise it will be different on each machine. more info The same thing will happen if you recycle the application’s pool on IIS. The old key will be disappeared. more info

Hi! I get the same error for every user, but not in Mozilla and Mozilla Developer Edition, only in MS Edge and Chrome. The error I get in the logs is as follows: Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {946d4fa4-6290-4104-a4d6-d0eb9dfa3006} was not found in the key ring. For more information go to http://aka.ms/dataprotectionwarning at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) --- End of inner exception stack trace --- at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)

A point to be considered is, it rarely happens on our production server, but it happens every time on our test server, where we set the same PasswordHash for all users. Now as far as I could trace it, the authentication is done successfully, but afterwards, when redirecting to a protected endpoint, this error happens and the user is unable to log in.

I didn’t read this entire thread, so I apologize if someone already suggested this…

One possible cause: If you are using IIS, make sure the application pool (Advanced Settings) has ‘Load User Profile’ set to True.

I also did that and the result was the same.

Same issue:

Blazor Net8 : Rendermode Auto (with server and client components)

Deployed Windows Server 2019 on 2 nodes.

When the app is deployed first time i get the exception, in the logs:

Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
 ---> System.Security.Cryptography.CryptographicException: The key {d8ffbea2-4fff-4fd2-ade3-f0fb72b71a12} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)

But somehow the app its up with no problems

Tried following the code recommended in the guides:

public static IServiceCollection ConfiguracionAntiforgeryToken(
    this IServiceCollection services,
    WebApplicationBuilder config
)
{
    var keysFolder = Path.Combine(config.Environment.ContentRootPath, "Keys");
    Directory.CreateDirectory(keysFolder);
    config
        .Services.AddDataProtection()
        .UseCryptographicAlgorithms(
            new AuthenticatedEncryptorConfiguration
            {
                EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
            }
        )
        .PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
        .SetApplicationName("MyWebsite")
        .SetDefaultKeyLifetime(TimeSpan.FromDays(90));
    return services;
}

But nothing changes, i get the error only when the app is deployed for the first time

Update: i think its related with this : #46124

Just for the record, I suppose I should mention that netcoreapp3.1 is out of support and wouldn’t be patched if that ended up being the fix. I’m tentatively operating on the assumption that @NitinSinghSF and @ChadEQ are seeing the same exception in 6.0 and 7.0, but it would be nice if they could confirm that they’re seeing the same symptoms - the problem follows particular users across devices / cookie wipes.

Hi

We have tried the following:

  1. Private browsing session

  2. Clearing cookies and cache

  3. On an iPad and iPhone

  4. On an android phone

  5. On another user’s laptop

We still run into the same error.

On Wed, 15 Nov 2023 at 8:34 AM, Andrew Casey @.***> wrote:

@weirdyang https://github.com/weirdyang If you’re in contact with the user, it might be interesting to ask them to try again after clearing their cookies.

@weirdyang https://github.com/weirdyang @NitinSinghSF https://github.com/NitinSinghSF @ChadEQ https://github.com/ChadEQ How is your key ring stored? Is it a file on disk? A blob in Azure Storage?

— Reply to this email directly, view it on GitHub https://github.com/dotnet/aspnetcore/issues/47185#issuecomment-1811612208, or unsubscribe https://github.com/notifications/unsubscribe-auth/AGDEEVXX32FPULLO3FNWH5TYEQEXRAVCNFSM6AAAAAAV2DUB7GVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQMJRGYYTEMRQHA . You are receiving this because you were mentioned.Message ID: @.***>

I had the same issue in asp.net 7.0 on windows/IIS. One instance. And no special characters in the user name.