Software Development

A journal for sharing all things software development related

Data Protection APIs and ValidateAntiForgeryToken / @Html.AntiForgeryToken

Tue, 16 Jul 2019 08:41 UTC by garethbrown

I recently ran into a requirement for using .NET core AntiForgeryTokens in a load balanced environment.

The [ValidateAntiForgeryToken] header and @Html.AntiForgeryToken() helper are dependant on ASP.NET core data protection APIs. Unless otherwise configured, these are automatically generated on a per-machine basis.

A potential means of managing data protection keys is to store a file in the file system along with the application and copy the key file to the application output directory. Note this is less secure than some other means of configuring the ASP.NET core data protections API's, and the below code assumes an unencrypted key.

	public void ConfigureServices(IServiceCollection services)
        string currentWorkingDirectory = Directory.GetCurrentDirectory();

        services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(currentWorkingDirectory)).DisableAutomaticKeyGeneration();

Run the above code once without .DisableAutomaticKeyGeneration() to generate the key file.

This will create a file with the format: key-guid-goes-here.xml. Where a file exists with a name in the correct format, ASP .NET core will use that file.

<?xml version="1.0" encoding="utf-8"?>
<key id="guid-goes-here" version="1">
  <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=, Culture=neutral, PublicKeyToken=adb9793829ddae60">
      <encryption algorithm="AES_256_CBC" />
      <validation algorithm="HMACSHA256" />
      <masterKey p4:requiresEncryption="true" xmlns:p4="">
        <!-- Warning: the key below is in an unencrypted form. -->

The information on this site is provided “AS IS” and without warranties of any kind either
express or implied. To the fullest extent permissible pursuant to applicable laws, the author disclaims all warranties, express or implied, including, but not limited to, implied warranties of merchantability, non-infringement and suitability for a particular purpose.

UI block loader
One moment please ...