DistributedCache extensions for Data Protection in ASP.NET Core

Repo: https://github.com/Visibilityltd/Visibility.AspNetCore.DataProtection.DistributedCache

This contains two simple classes:

  • DistributedCache DataProtection Provider
  • DistributedCache PropertiesDataFormat

DataProtection Provider

When having a distributed and stateless ASP.NET Core web server, you need to have your Data Protection keys saved to a location to be shared among your servers.

The default providers that the ASP.NET Core team provides are here

I was just going to use Redis but the implementation is hard-coded to Redis. I’m already using the DistributedCache Redis provider, so why not just link in to that? I don’t need to configure two different things now.

Usage

services.AddDataProtection()
.PersistKeysToDistributedCache();

Boom, now if you’re using IDistributedCache you now persist your generated DataProtection keys there.

DistributedCache PropertiesDataFormat

Another issue is that the state on the URL can used for Authentication can be large. Why not use cache?

This is inspired and mostly copied from: https://github.com/IdentityServer/IdentityServer4/issues/407

Usage

Useful for any Authentication middleware. You need to hook it into the AuthenticationOptions for your protocol like so:

I’m using CAS Authentication

var dataProtectionProvider = app.ApplicationServices.GetRequiredService();
var distributedCache = app.ApplicationServices.GetRequiredService();

var dataProtector = dataProtectionProvider.CreateProtector(
typeof(CasAuthenticationMiddleware).FullName,
typeof(string).FullName, schemeName,
"v1");

//TODO: think of a better way to create
var dataFormat = new DistributedPropertiesDataFormat(distributedCache, dataProtector);

...

app.UseCasAuthentication(x =>
{
x.StateDataFormat = dataFormat;
...
};

OpenId and OAuth have StateDataFormat in their options. I’m sure others do too.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s