I have an ASP.NET Core application hosted in IIS in an Azure VM. I call the extension method to persist they key to Azure but nothing is ever stored there and the application seems to still be using local keys. I followed the example here: http://intellitect.com/staying-logged-across-azure-app-service-swap/ exactly. As a matter of fact, when I test the code in a console application, persistence works fine. However, when I run the ASP.NET Core app with this code, nothing ever gets persisted to Azure. Any ideas why?
问题:
回答1:
Please check the order of registering MVC service and DataProtection service. Registering DataProtection service must be before registering MVC service. Code below is for your reference.
// Add DataProtection Service
if (storageUrl != null && sasToken != null && containerName != null && applicationName != null && blobName != null)
{
// Create the new Storage URI
Uri storageUri = new Uri($"{storageUrl}{sasToken}");
//Create the blob client object.
CloudBlobClient blobClient = new CloudBlobClient(storageUri);
//Get a reference to a container to use for the sample code, and create it if it does not exist.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists();
services.AddDataProtection()
.SetApplicationName(applicationName)
.PersistKeysToAzureBlobStorage(container, blobName);
}
// Add framework services.
services.AddMvc();
回答2:
I marked the above response as an answer because it's correct and an important point. However, the real answer to this question is key data is not persisted just because the app starts up and you called PersistKeysToAzureBlobStorage (or any other PersistToXXX method). That's just for configuration of data protection. You can say it's "lazy". The key data will be generated with your code or the framework first calls Protect/Unprotect as in the following:
var protector = provider.CreateProtector("Some Purpose");
var enc = protector.Protect("Hello World");
...
protector.Unprotect(enc);
回答3:
The marked answer helped me to debug the issue I was having with keys not being persisted to blob storage.
In my case it was the lack of a root element in the existing blob/xml.
If there is an existing blob that is being referenced, it must contain the following content in order for the data protection library to populate it with the keys upon lazy initialisation:
<?xml version="1.0" encoding="utf-8"?><repository></repository>
The documentation doesn't mention this.