本文整理汇总了C#中ServiceCollection.AddDataProtection方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddDataProtection方法的具体用法?C# ServiceCollection.AddDataProtection怎么用?C# ServiceCollection.AddDataProtection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.AddDataProtection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InitProtection
public static MySafe InitProtection()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("."))
.SetDefaultKeyLifetime(TimeSpan.FromDays(20))
.ProtectKeysWithDpapi();
IServiceProvider services = serviceCollection.BuildServiceProvider();
return ActivatorUtilities.CreateInstance<MySafe>(services);
}
示例2: GetDataProtectionProvider
/// <summary>
/// This follows the same initialization that is provided when <see cref="IDataProtectionProvider"/>
/// is initialized within ASP.NET 5.0 Dependency Injection.
/// </summary>
/// <returns>A fully initialized <see cref="IDataProtectionProvider"/>.</returns>
internal static IDataProtectionProvider GetDataProtectionProvider()
{
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
IServiceProvider services = serviceCollection.BuildServiceProvider();
return services.GetDataProtectionProvider();
}
示例3: Main
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
// create an instance of MyClass using the service provider
var instance = ActivatorUtilities.CreateInstance<MyClass>(services);
instance.RunSample();
}
示例4: CreateInstance_DoesNotForwardIfClassDoesNotExist
public void CreateInstance_DoesNotForwardIfClassDoesNotExist()
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
var activator = services.GetActivator();
// Act & Assert
var name = "Microsoft.AspNet.DataProtection.RC1ForwardingActivatorTests+NonExistentClassWithParameterlessCtor, Microsoft.AspNet.DataProtection.Test";
var exception = Assert.ThrowsAny<Exception>(()=> activator.CreateInstance<object>(name));
Assert.Contains("Microsoft.AspNet.DataProtection.Test", exception.Message);
}
示例5: GetDataProtector
/// <summary>
/// This follows the same initialization that is provided when <see cref="IDataProtectionProvider"/>
/// is initialized within ASP.NET Core 1.0 Dependency Injection.
/// </summary>
/// <returns>A fully initialized <see cref="IDataProtectionProvider"/>.</returns>
public static IDataProtector GetDataProtector()
{
if (_dataProtector != null)
{
return _dataProtector;
}
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
IServiceProvider services = serviceCollection.BuildServiceProvider();
IDataProtectionProvider provider = services.GetDataProtectionProvider();
IDataProtector instance = provider.CreateProtector(Purpose);
Interlocked.CompareExchange(ref _dataProtector, instance, null);
return _dataProtector;
}
示例6: CreateInstance_ForwardsToNewNamespaceIfExists
public void CreateInstance_ForwardsToNewNamespaceIfExists()
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
var activator = services.GetActivator();
// Act
var name = "Microsoft.AspNet.DataProtection.RC1ForwardingActivatorTests+ClassWithParameterlessCtor, Microsoft.AspNet.DataProtection.Test";
var instance = activator.CreateInstance<object>(name);
// Assert
Assert.IsType<ClassWithParameterlessCtor>(instance);
}
示例7: Main
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"))
.ProtectKeysWithDpapi()
.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));
}
示例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();
// 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}");
}
}
示例9: InternalConfigureServicesAndCreateProtectionProvider
/// <summary>
/// Provides a default implementation of required services, calls the developer's
/// configuration overrides, then creates an <see cref="IDataProtectionProvider"/>.
/// </summary>
internal IDataProtectionProvider InternalConfigureServicesAndCreateProtectionProvider()
{
// Configure the default implementation, passing in our custom discriminator
var services = new ServiceCollection();
services.AddDataProtection();
services.AddSingleton<IApplicationDiscriminator>(new SystemWebApplicationDiscriminator());
// Run user-specified configuration and get an instance of the provider
ConfigureServices(services);
var provider = CreateDataProtectionProvider(services.BuildServiceProvider());
if (provider == null)
{
throw new InvalidOperationException(Resources.Startup_CreateProviderReturnedNull);
}
// And we're done!
return provider;
}
示例10: 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");
}
示例11: 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>();
}
示例12: AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId
public void AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId(
string applicationId,
string expectedCookieName)
{
// Arrange
var serviceCollection = new ServiceCollection();
serviceCollection.AddAntiforgery();
serviceCollection
.AddDataProtection()
.SetApplicationName(applicationId);
var services = serviceCollection.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
// Assert
Assert.Equal(expectedCookieName, cookieName);
}
示例13: Main
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
// get an IDataProtector from the IServiceProvider
var protector = services.GetDataProtector("Contoso.Example.v2");
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}");
}
示例14: 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;
}
示例15: 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
.AddDataProtection()
.SetApplicationName("HelloWorldApp");
var services = serviceCollection.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
// Assert
Assert.Equal("antiforgery", cookieName);
}