Using Antiforgery in ASP.NET Core and got error - the antiforgery token could not be decrypted
Asked Answered
L

7

26

My ASP.Net Core MVC application have added Antiforgery middleware like below:

startup.cs

services.AddMvc();
services.AddSession();
services.AddCaching();
services.AddSession(o =>
{
  o.IdleTimeout = TimeSpan.FromMinutes(120);
});
services.AddAntiforgery();

I've added below in the view and controller

View:

<form action="/Home/Login" method="post" id="staff-login" autocomplete="off">
    @Html.AntiForgeryToken()
 ...

Controller

[HttpPost, ValidateAntiForgeryToken] 
public IActionResult Login(IFormCollection formCollection) 
{...}

The problem is users always get below when users come across different forms.

System.InvalidOperationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} was not found in the key ring.

I found a solution which suggests setting a static pair of validation/decryption key in the web.config but it seems this solution is only for classic asp.net application. How should I do in ASP.Net core?

Lowbrow answered 8/2, 2017 at 1:18 Comment(1)
Check this explanation: learn.microsoft.com/en-us/aspnet/core/security/data-protection/…. You may require reusing same key value there (by persisting key to a specific directory path).Castera
R
36

I've had exactly that error on a ASP .net core app hosted on a linux container.

From the docs it would seem if you don't meet certain criteria the keys are only persisted in the process - but that even for me was not working.

First the error occurred with the default setup.
I then added specific configuration for the keys on the filesystem:

            services.AddDataProtection()
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/my-af-keys/"));

This also didn't fix the issue I had to set an application name:

            services.AddDataProtection()
                .SetApplicationName("fow-customer-portal")
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/dpkeys/"));

I haven't confirmed but its possible nature of the LXC hosting means .net core cannot persist the identity of the app.

Rebak answered 6/11, 2017 at 19:2 Comment(2)
This works, however once you change the web.config entry from <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> to <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Test" /> it no longer works and produces the following warning: System.Security.Cryptography.CryptographicException: The key {4ec49003-9829-4b03-bf2f-5756943cff99} was not found in the key ringOxonian
7 years later and I'm still fixing random AntiForgery issues with obscure one-liners like SetApplicationName(). Thank you, sir.Horsemint
K
22

I've had this because I started using the application on a localhost port and then was trying to use it in docker with the same port. By then I had cookies that specified the key generated by my machine, so It wouldn't work on docker.

TL;DR clear your cookies if you ever used that domain/port from other machines.

Kinnikinnick answered 3/2, 2019 at 12:5 Comment(1)
This was my problem too, thought it was with the anti-forgery middleware app.UseAntiforgery(); that is added by default in the templates with ASP.NET Core 8. Not intuitive but obvious once you realize it!Dedra
N
1

AWS, Azure and Google Cloud have libraries to make use of their data stores.

Azure and also to make use of Redis: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-providers?view=aspnetcore-6.0&tabs=visual-studio

AWS: https://aws.amazon.com/blogs/developer/aws-ssm-asp-net-core-data-protection-provider/

services
.AddDataProtection()
.PersistKeysToAWSSystemsManager("/App/DataProtection")
.UseCryptographicAlgorithms(
    new AuthenticatedEncryptorConfiguration
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    }
);
Nealy answered 1/9, 2022 at 8:52 Comment(0)
H
0

What worked for me was using a new user account instead of NETWORK SERVICE as the error message included this:

System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\config\systemprofile' is denied.

Heise answered 4/6, 2020 at 14:37 Comment(0)
F
0

I had this issue when I was trying to host my application on docker localhost. Connecting to application with port 80 (http) will throw error on POST / PUT / DEL requests when using Chrome browser.

If you're just trying to see the output and you're on development, use FireFox instead.

Flip answered 15/8, 2023 at 8:15 Comment(0)
M
0

If you see this error when hosting an application via IIS, try setting "Load User Profile" to "True" in the Application Pool settings.

See Gitlab Issue #8509 - Cryptography Errors

and Gitlab Issue #47185 - The antiforgery token could not be decrypted - Only for specific user

Marianelamariani answered 5/7 at 9:56 Comment(0)
M
-2

I as having similar problem in a linux container running .net core 5 app on azure, and opening my browser in private mode solved this issue.

Melissa answered 11/8, 2021 at 11:31 Comment(1)
Resolved my issue while I was using docker-compose to run several apps. I am guessing data protection wasn't implemented and ASP.NET still generated a forgery token and added it to the cookie. On Linux environment within docker those tokens can't be used for some reason, so they need to be stored. However after I implemented storing the keys in the database, my client still had the old forgery token in the cookies and server wasn't able to decrypt that. Clearing the cookies, and storing the keys in a persistent way resolved my issue.Agoraphobia

© 2022 - 2024 — McMap. All rights reserved.