Journal: Software Development

Email: mail@appsoftware.com

Software development notes and articles

A journal for sharing all things software development related


Data Protection APIs and ValidateAntiForgeryToken / @Html.AntiForgeryToken

Tue, 16 Jul 2019 08:41 UTC

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">
  <creationDate>2019-01-01T00:00:00.000000Z</creationDate>
  <activationDate>2019-01-01T00:00:00.000000Z</activationDate>
  <expirationDate>3019-01-01T00:00:00.000000Z</expirationDate>
  <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
    <descriptor>
      <encryption algorithm="AES_256_CBC" />
      <validation algorithm="HMACSHA256" />
      <masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection">
        <!-- Warning: the key below is in an unencrypted form. -->
        <value>xxxx-master-key-goes-here-xxxx</value>
      </masterKey>
    </descriptor>
  </descriptor>
</key>

https://stackoverflow.com/questions/50843706/data-protection-in-asp-net-core-2-1-only-works-on-one-machine

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.