【发布时间】:2017-04-12 11:26:06
【问题描述】:
我很难理解数据保护 API。
我想在集群环境(服务结构)中设置一些网络核心 Web 应用程序。以前您要做的只是确保每台机器在其 web.config 中具有相同的密钥。简单的。有了新的数据保护 API,它似乎有点(很多!)更多的参与。
从文档here 看来,它应该像使用适当的证书设置数据保护服务一样简单。
不过我试过了:
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
string thumbPrint = "XXXXXXXXXXXX";
serviceCollection.AddDataProtection()
.ProtectKeysWithDpapiNG($"CERTIFICATE=HashId:{thumbPrint}", flags: Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGProtectionDescriptorFlags.None);
var services = serviceCollection.BuildServiceProvider();
// create an instance of MyClass using the service provider
var instance = ActivatorUtilities.CreateInstance<MyClass>(services);
instance.RunSample();
}
public class MyClass
{
IDataProtector _protector;
// the 'provider' parameter is provided by DI
public MyClass(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Contoso.MyClass.v1");
}
public void RunSample()
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
// protect the payload
string protectedPayload = _protector.Protect(input);
Console.WriteLine($"Protect returned: {protectedPayload}");
// unprotect the payload
string unprotectedPayload = _protector.Unprotect(protectedPayload);
Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
Console.ReadLine();
}
}
我只是得到一个例外
System.InvalidOperationException occurred
HResult=0x80131509
Message=No service for type 'Microsoft.AspNetCore.DataProtection.Repositories.IXmlRepository' has been registered.
经过一番挖掘后发现这是因为没有为密钥指定持久存储。
这里有什么建议?我是否应该将我的密钥保存到某个中心位置(即我的所有应用程序都可以使用的共享)。如果有,原因是什么?
【问题讨论】:
-
您需要明确密钥的保存位置。 docs.microsoft.com/en-gb/aspnet/core/security/data-protection/… - 例如尝试
.PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"));。 -
@Christo 谢谢!完全以为我更新了这个问题,我最终将我的密钥保存到 AzureStorage。
标签: c# asp.net asp.net-core data-protection