0

Edit The original question I asked was "JsonSerializer.Serialize throws 'Server failed to authenticate the request.' How can I prevent JsonSerializer from using encryption in unit tests?"

Then I realized I used authentication in the model being serialized. Sorry for the poor question. I edited the question. Perhaps someone will find it useful that I found a strange error message and worked through it.

Original Question: I am moving code from on-prem to Azure. At first I removed encryption that used the on-prem certificate. It's time to put it back, but in the Azure way. I am attempting to protect keys with Azure Key Vault as described in https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.1 To get started I added this to ConfigureServices in Startup.cs:

using Microsoft.AspNetCore.DataProtection;
...
services.AddDataProtection()
    .PersistKeysToAzureBlobStorage(new Uri("https://ddd.blob.core.windows.net/ddd-dev-keystore?redacted"));

As soon as I did some of my tests fail because of logging code:

_logger.LogDebug("Model is {model}", JsonSerializer.Serialize(model));

That particular model is not encrypted and does not need to touch any encryption / decryption code. Later I will have some data that will need encryption, but I need control over this.

How can I prevent JsonSerializer from using encryption?

Edit Forgot I added this to the model in question:

public class MyModel
{
    private readonly IDataProtector _dataProtector;

    public MyModel(IDataProtectionProvider dataProtectionProvider, ...)
    {
        _dataProtector = dataProtectionProvider.CreateProtector(Models.MyPlan.EncryptionPurpose);
    ...
    }

So part of the mystery is solved. This question has suddenly become much simpler. It is now - how do I write tests with IDataProtectionProvider in my DI container? And that, dear friends, is already answered elsewhere.

rjacobsen0
  • 1,287
  • 13
  • 25

1 Answers1

1

This answer was also helpful.

I solved this by adding this code to the test harness startup

public class CustomTestWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder<TStartup>(null);
    }
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) =>
        {
            services.AddSingleton<IDataProtectionProvider, EphemeralDataProtectionProvider>();
        }
    }
}

Notice the innermost line where it says AddSingleton and I add an IDataProtectionProvider? That's the magic. It replaces the real provider with one that does not access Azure or any other storage for keys.

It remains to be seen if serializing the model makes it encrypted or not, but the tests are passing now.

rjacobsen0
  • 1,287
  • 13
  • 25