Search code examples
blazorantiforgerytokenweb-farm

Antiforgery token with Blazor .Net 8 on a web farm - machinekey not used


I'd like to deploy a Blazor Web App (.Net 8) on a web farm (windows + IIS). If I deploy the app on a single machine, it works fine. But when many servers are used with load-balancing, then an Antiforgery error is launched when accessnig pages that use antiforgery:

Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery - 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 {d1a4d3f6-a151-4829-8561-e7e49e3c1341} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning

I've read this article on Anti forgery token and manchine key and applied what the author suggested (it means forcing the same machine key on IIS on all servers), but unfortunately it doesn't resolve the issue.

Am I missing something?

Thank you


Solution

  • You need to store the Data Protection Key ring in some persistent storage, like a database or as a file somewhere.

    I did a blog post about how to store it in Azure Key Vault (As a learning exercise) : Storing the ASP.NET Core Data Protection Key Ring in Azure Key Vault

    However, this is not an example of production quality. I suggest you use one of the more hardened storage alternatives as described here: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-7.0

    The picture below shows an example of what it can look like in production and if you want to share cookies across service instances.

    enter image description here