Back to Blog
Feb 07, 2023

Ensure users remain logged in on Azure Kubernetes Service with AddDataProtection()

Written by Zack Schwartz

Logged in sessions are lost

Have you ever deployed a .NET application that allows users to log in, only to run into issues when scaling it out? It can be frustrating when everything seems to be working fine, but then users randomly get logged out or have inconsistent login status after refreshing the page. But don't worry, there's a simple explanation for this.

When you scale out your application, you end up with multiple instances running at the same time. However, the cookie or session that tracks the user's login information is only tied to the individual instance, not the entire cluster. This means that when a user makes a request, they could hit any one of the instances, resulting in a lost session.

To solve this problem, you need a way to maintain the user's logged in session with the cluster as a whole, no matter which instance they hit. And that's what we'll be diving into in this post!

AddDataProtection() saves the day

The way to solve this is to introduce the AddDataProtection() functionality to your application. Here is the base line article: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-7.0. The idea is that all of the machines running in the cluster have access to a common DataProtectionKey. This key is used to create all of the sessions when a user is logged in.

.NET supports several methods for sharing the data protection key among all of the machines. These methods include:

  • Azure Key Vault
  • File System
  • Database

In my opinion, if you already are using Entity Framework with a database, then the third option is the easiest. Implementing this is straight forward.

Add a line in your Startup.cs:

services.AddDataProtection().SetApplicationName("Raytha").PersistKeysToDbContext<RaythaDbContext>();

You can replace "Raytha" and the RaythaDbContext with names specific to your application.

Then, you also need to update your DbContext class to implement the IDataProtectionKeyContext interface.




Likely you will need to include an Entity Framework Migration as a result. However, I feel this is easier than setting up a shared Azure Key Vault or shared file system.

Hope this helps anyone might be having issues with people staying logged in to their application.

picture of the author
Zack Schwartz @apexdodge

ENTREPRENEUR & SOFTWARE ENGINEER, AUSTIN, TX
I enjoy tackling a wide array of business challenges ranging from front line product support and operations to sales and marketing efforts. My core expertise is in software development building enterprise level web applications.


Subscribe to the Raytha newsletter