Tech Sharing :: How resolve Antiforgery in WebFarm

246 阅读1分钟

1. What's Antiforgery?

Cross Site Request Forgery (aka CSRF or XSRF) is one of the most common attacks in which the user is tricked into executing an unwanted action through his browser on his behalf, in one of the sites he is currently authenticated.

ASP.Net Core contains an Antiforgery package that can be used to secure your application against this particular risk. For those who have used earlier versions of ASP.Net will see that things have changed a bit in the new framework.

Reference Link: www.dotnetcurry.com/aspnet/1343…

NOTE: Antiforgery is defaultly introduced to your app when you call below codes.

AddMvc()
AddRazorPages()
...

2. What's webfarm?

Shortly word, deploy you asp.net or asp.net core web app in a cluster, and there is a load-balancer before all your nodes.

Reference: docs.microsoft.com/en-us/aspne…

3. Why we received the anti-forgery exception?

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 {2f920311-e27d-490b-89ef-a7478e738f12} was not found in the key ring.
...

Since in every form, the protection-key is introduced by default, like a hidden element. It will only validate for the initial node (instance) when you deploy your app in a web-farm mode.

4. How to resolve that issue?

  • In asp.net time
    You need to configure machineKey in the web.config file.
  • In asp.net core time
    The machineKey is replaced by DataProtection mode in the asp.net core. Every nodes in the cluster | web-farm should share the same protection-key. The protection-key is used to protect the app avoid CSRF.

How you can persist the protection-key

  • File-system
  • Registry
  • Azure
  • Redis
  • Customize IXmlRepository

How to share with nodes

  • File-system: Save to shared url
  • Azure
  • Redis
  • DB

Reference Links