24
votes

In ASP.NET (not core) I would normally add a machineKey to the web.config so that I could perform some functions on a local machine instead of the server so that database/callback operations would use the same key. Eg

<system.web>
  <machineKey validationKey="*********" 
              decryptionKey="*********" 
              validation="HMACSHA256" 
              decryption="AES" />
</system.web>

Please can someone advise how this can be done in ASP.NET Core 2.0?

4
Duplicated question, a "more understandable" answer here: stackoverflow.com/a/46894509/7149454Nick Kovalsky
@pathdongle did you figure this out? I can't find any examples for Data Protection API where you can set a shared validationKey and decryptionKeyYodacheese
you should add Data Protection, read this answerD.L.MAN

4 Answers

16
votes

You need to use DataProtection APis now:

The ASP.NET Core data protection stack provide a simple, easy to use cryptographic API a developer can use to protect data, including key management and rotation.

Samples could be found in official DataProtection repo.

The same approach, by the way, works with ASP.NET: Replacing <machineKey> in ASP.NET


The data protection system is built upon two core concepts - a data protection provider (represented by the IDataProtectionProvider interface), which is used to create a data protector (represented by the IDataProtector interface) by CreateProtector method. The data protector is used to encrypt and decrypt data.

To register IDataProtectionProvider into DI use .AddDataProtection method:

public void ConfigureServices(IServiceCollection services)
{
    // Adds data protection services
    services.AddDataProtection();
    ...
}
5
votes

You can find good examples at https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-providers?view=aspnetcore-2.2&tabs=visual-studio

I used my database context to persist the keys across multiple instances.

DbContext.cs

public class MyContext : IDataProtectionKeyContext
{
  ...
  // This maps to the table that stores keys.
  public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddDataProtection().PersistKeysToDbContext<MyContext>();
}
3
votes

For legacy purposes where you want to build out your ASP.NET Core applications based on some classic ASP.NET application that is responsible for generating the authentication cookies, there is an open source library available that enables you to consume these legacy cookies into your ASP.NET Core application. The developers have used the .NET Framework reference implementation to build their own Machinekey based encryption/decryption logic. See https://github.com/synercoder/FormsAuthentication

-1
votes

in asp.net Core you should set Data Protection system.

for more information read this answer.