本文整理汇总了C#中ServiceCollection.ConfigureDataProtection方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.ConfigureDataProtection方法的具体用法?C# ServiceCollection.ConfigureDataProtection怎么用?C# ServiceCollection.ConfigureDataProtection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.ConfigureDataProtection方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
serviceCollection.ConfigureDataProtection(configure =>
{
// point at a specific folder and use DPAPI to encrypt keys
configure.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"));
configure.ProtectKeysWithDpapi();
});
var services = serviceCollection.BuildServiceProvider();
// perform a protect operation to force the system to put at least
// one key in the key ring
services.GetDataProtector("Sample.KeyManager.v1").Protect("payload");
Console.WriteLine("Performed a protect operation.");
Thread.Sleep(2000);
// get a reference to the key manager
var keyManager = services.GetService<IKeyManager>();
// list all keys in the key ring
var allKeys = keyManager.GetAllKeys();
Console.WriteLine($"The key ring contains {allKeys.Count} key(s).");
foreach (var key in allKeys)
{
Console.WriteLine($"Key {key.KeyId:B}: Created = {key.CreationDate:u}, IsRevoked = {key.IsRevoked}");
}
// revoke all keys in the key ring
keyManager.RevokeAllKeys(DateTimeOffset.Now, reason: "Revocation reason here.");
Console.WriteLine("Revoked all existing keys.");
// add a new key to the key ring with immediate activation and a 1-month expiration
keyManager.CreateNewKey(
activationDate: DateTimeOffset.Now,
expirationDate: DateTimeOffset.Now.AddMonths(1));
Console.WriteLine("Added a new key.");
// list all keys in the key ring
allKeys = keyManager.GetAllKeys();
Console.WriteLine($"The key ring contains {allKeys.Count} key(s).");
foreach (var key in allKeys)
{
Console.WriteLine($"Key {key.KeyId:B}: Created = {key.CreationDate:u}, IsRevoked = {key.IsRevoked}");
}
}
示例2: GenerateProtectedKeyToFile
public static void GenerateProtectedKeyToFile(string file)
{
var lServiceCollection = new ServiceCollection();
lServiceCollection.AddDataProtection();
lServiceCollection.ConfigureDataProtection(configure =>
{
// persist keys to a specific directory
configure.PersistKeysToFileSystem(new DirectoryInfo(@".\keys"));
// uncomment when doing this from different application
//configure.SetApplicationName("SameAppName");
});
var lServices = lServiceCollection.BuildServiceProvider();
// create an instance of MyClass using the service provider
var lKeyUtils = ActivatorUtilities.CreateInstance<RSAKeyUtils>(lServices);
lKeyUtils.GenerateKeyAndSave("authtoken.key");
}
示例3: AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId
public void AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId(
string applicationId,
string expectedCookieName)
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddAntiforgery();
serviceCollection.ConfigureDataProtection(o => o.SetApplicationName(applicationId));
var services = serviceCollection.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
// Assert
Assert.Equal(expectedCookieName, cookieName);
}
示例4: DataProtectionProvider
/// <summary>
/// Creates an <see cref="DataProtectionProvider"/> given a location at which to store keys and an
/// optional configuration callback.
/// </summary>
/// <param name="keyDirectory">The <see cref="DirectoryInfo"/> in which keys should be stored. This may
/// represent a directory on a local disk or a UNC share.</param>
/// <param name="configure">An optional callback which provides further configuration of the data protection
/// system. See <see cref="DataProtectionConfiguration"/> for more information.</param>
public DataProtectionProvider(DirectoryInfo keyDirectory, Action<DataProtectionConfiguration> configure)
{
if (keyDirectory == null)
{
throw new ArgumentNullException(nameof(keyDirectory));
}
// build the service collection
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
serviceCollection.ConfigureDataProtection(configurationObject =>
{
configurationObject.PersistKeysToFileSystem(keyDirectory);
configure?.Invoke(configurationObject);
});
// extract the provider instance from the service collection
_innerProvider = serviceCollection.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
}
示例5: Main
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
serviceCollection.ConfigureDataProtection(configure =>
{
// point at a specific folder and use DPAPI to encrypt keys
configure.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"));
configure.ProtectKeysWithDpapi();
configure.AddKeyEscrowSink(sp => new MyKeyEscrowSink(sp));
});
var services = serviceCollection.BuildServiceProvider();
// get a reference to the key manager and force a new key to be generated
Console.WriteLine("Generating new key...");
var keyManager = services.GetService<IKeyManager>();
keyManager.CreateNewKey(
activationDate: DateTimeOffset.Now,
expirationDate: DateTimeOffset.Now.AddDays(7));
}
示例6: Setup
private void Setup()
{
var services = new ServiceCollection();
//http://docs.asp.net/en/latest/security/data-protection/configuration/overview.html
//If you change the key persistence location, the system will no longer automatically encrypt keys
// at rest since it doesn’t know whether DPAPI is an appropriate encryption mechanism.
services.ConfigureDataProtection(configure =>
{
//string pathToCryptoKeys = @"C:\_joe\__projects\__cloudscribe\_code\cloudscribe\src\example.WebApp\dp_keys\";
// these keys are not encrypted at rest
// since we have specified a non default location
// that also makes the key portable so they will still work if we migrate to
// a new machine (will they work on different OS? I think so)
// this is a similar server migration issue as the old machinekey
// where we specified a machinekey in web.config so it would not change if we migrate to a new server
//configure.PersistKeysToFileSystem(
// new DirectoryInfo(pathToCryptoKeys)
// );
//configure.ProtectKeysWithCertificate("thumbprint");
//configure.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
///configure.
});
//IDataProtectionProvider dataProtectionProvider
services.AddDataProtection();
serviceProvider = services.BuildServiceProvider();
dataProtectionProvider = serviceProvider.GetService<IDataProtectionProvider>();
rawProtector = dataProtectionProvider.CreateProtector("sts.Licensing.Web.KeyPairManager");
persistentProtector = rawProtector as IPersistedDataProtector;
didSetup = true;
}
示例7: AntiforgeryOptionsSetup_UserOptionsSetup_CanSetCookieName
public void AntiforgeryOptionsSetup_UserOptionsSetup_CanSetCookieName()
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.Configure<AntiforgeryOptions>(o =>
{
Assert.Null(o.CookieName);
o.CookieName = "antiforgery";
});
serviceCollection.AddAntiforgery();
serviceCollection.ConfigureDataProtection(o => o.SetApplicationName("HelloWorldApp"));
var services = serviceCollection.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
// Assert
Assert.Equal("antiforgery", cookieName);
}
示例8: Main
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
serviceCollection.ConfigureDataProtection(configure =>
{
// point at a specific folder and use DPAPI to encrypt keys
configure.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"));
configure.ProtectKeysWithDpapi();
});
var services = serviceCollection.BuildServiceProvider();
// get a protector and perform a protect operation
var protector = services.GetDataProtector("Sample.DangerousUnprotect");
Console.Write("Input: ");
byte[] input = Encoding.UTF8.GetBytes(Console.ReadLine());
var protectedData = protector.Protect(input);
Console.WriteLine($"Protected payload: {Convert.ToBase64String(protectedData)}");
// demonstrate that the payload round-trips properly
var roundTripped = protector.Unprotect(protectedData);
Console.WriteLine($"Round-tripped payload: {Encoding.UTF8.GetString(roundTripped)}");
// get a reference to the key manager and revoke all keys in the key ring
var keyManager = services.GetService<IKeyManager>();
Console.WriteLine("Revoking all keys in the key ring...");
keyManager.RevokeAllKeys(DateTimeOffset.Now, "Sample revocation.");
// try calling Protect - this should throw
Console.WriteLine("Calling Unprotect...");
try
{
var unprotectedPayload = protector.Unprotect(protectedData);
Console.WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)}");
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
// try calling DangerousUnprotect
Console.WriteLine("Calling DangerousUnprotect...");
try
{
IPersistedDataProtector persistedProtector = protector as IPersistedDataProtector;
if (persistedProtector == null)
{
throw new Exception("Can't call DangerousUnprotect.");
}
bool requiresMigration, wasRevoked;
var unprotectedPayload = persistedProtector.DangerousUnprotect(
protectedData: protectedData,
ignoreRevocationErrors: true,
requiresMigration: out requiresMigration,
wasRevoked: out wasRevoked);
Console.WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)}");
Console.WriteLine($"Requires migration = {requiresMigration}, was revoked = {wasRevoked}");
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
}