Cabin covered in snow

ASP NET Core Data Protection in a distrubuted environment

I noticed that if I redeploy my ASP NET Core Razor Pages app when it is hosted in a distributed environment, all my users were signed out of their current session as well issues with ASP NET Core AntiForgery (CSRF) protection.

When the Data Protection system is initialized, it applies default settings based on the operational environment. These settings are generally appropriate for apps running on a single machine. There are cases where a developer may want to change the default settings:

  • The app is spread across multiple machines.
  • For compliance reasons.

And in the case of AWS Lambda it is apperant since AWS might recycle and spawn new containers at any time, on any machine.

To combat this issue we need to store the encryption keys externally and set an application name. Without the setting the application name ASP NET Core will by default use the physical path of the application as an unique application identifier and in a distributed environment this will be problematic.

Fortunately AWS can help us out with this using the AWS Parameter Store.

Start by giving your application access to Parameter Store using IAM. The policy can look like this depending on how granular you want to be.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SSMRule1",
"Effect": "Allow",
"Action": [
"ssm:GetParametersByPath"
],
"Resource": "*"
}
]
}

Then install the Amazon.AspNetCore.DataProtection.SSM nuget package.

Install-Package Amazon.AspNetCore.DataProtection.SSM

Now you can add below code in Startup.cs to modify the data protection behavior.

 services.AddDataProtection()
.PersistKeysToAWSSystemsManager("/MyApplication/DataProtection")
.SetApplicationName("MyApplication");

Now it is all done!

If you navigate to Systems Manager > Parameter Store in the AWS Console you should see your new secure parameter.