public static ConfigurationManager AddTyrConfiguration(this ConfigurationManager configuration) { if (configuration.GetServiceId() == null) { // A hack to simpler get the service value if not set. var entryAssemblyName = Assembly.GetEntryAssembly()?.FullName; var parts = entryAssemblyName?.Split('.', ','); if (parts != null && parts.Length >= 3 && parts[0] == "TypingRealm" && parts[2] == "Api") { configuration.AddInMemoryCollection(new[] { new KeyValuePair <string, string>("ServiceId", parts[1].ToLowerInvariant()) }); } } if (!DebugHelpers.IsDeployment()) { // This prevents EF migration from working. var serviceId = configuration.GetServiceId(); if (string.IsNullOrWhiteSpace(serviceId)) { throw new InvalidOperationException("ServiceId should be specified for service."); } } return(configuration); }
public void ConfigureServices_should_configure_signalR() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["ConnectionStrings:DefaultConnection"] = Guid.NewGuid().ToString(), ["DbType"] = "InMemory", ["SignalR:UseMessagePack"] = "true", ["SignalR:RedisConnectionString"] = "localhost:6379" }); var environementMock = new Mock <IWebHostEnvironment>(); var services = new ServiceCollection(); services.AddTransient <IConfiguration>(p => configuration); services.AddTheIdServer(configuration); var provider = services.BuildServiceProvider(); var hubProtocolResolver = provider.GetServices <IHubProtocolResolver>(); Assert.NotNull(hubProtocolResolver); var hubLifetimeManager = provider.GetServices <RedisHubLifetimeManager <ProviderHub> >(); Assert.NotNull(hubLifetimeManager); }
public void Configure_should_configure_keys_rotation_azure_storage() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["IdentityServer:Key:Type"] = KeyKinds.KeysRotation.ToString(), ["IdentityServer:Key:StorageKind"] = StorageKind.AzureStorage.ToString(), ["IdentityServer:Key:StorageConnectionString"] = "https://azure.com?sv=test" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); Assert.Null(host.Services.GetService <IXmlRepository>()); }
public void Configure_should_configure_keys_rotation_storage_cert_file_protection() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["IdentityServer:Key:Type"] = KeyKinds.KeysRotation.ToString(), ["IdentityServer:Key:StorageKind"] = StorageKind.None.ToString(), ["IdentityServer:Key:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(), ["IdentityServer:Key:KeyProtectionOptions:X509CertificatePath"] = "theidserver.pfx", ["IdentityServer:Key:KeyProtectionOptions:X509CertificatePassword"] = "******" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); Assert.Null(host.Services.GetService <IXmlRepository>()); }
public void Configure_should_configure_data_protection_storage_dpaping_protection_with_sid() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(), ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.WindowsDpApiNg.ToString(), ["DataProtectionOptions:KeyProtectionOptions:WindowsDpApiNgSid"] = "test" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); Assert.Null(host.Services.GetService <IXmlRepository>()); }
public void Configure_should_configure_data_protection_storage_cert_protection() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(), ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(), ["DataProtectionOptions:KeyProtectionOptions:X509CertificateThumbprint"] = "test" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); Assert.Throws <InvalidOperationException>(() => WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build()); }
public void Configure_should_configure_data_protection_azure_storage() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["DataProtectionOptions:StorageKind"] = StorageKind.AzureStorage.ToString(), ["DataProtectionOptions:StorageConnectionString"] = "https://md-3r0d4kzc5jhz.blob.core.windows.net/s3vffgdlczdj/abcd?sv=2017-04-17&sr=b&si=e931bb4b-8a79-4119-b4bb-8b2c1b763369&sig=SIGNATURE_WILL_BE_HERE" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); Assert.Null(host.Services.GetService <IXmlRepository>()); }
public void UseDatabaseFromConfiguration_should_configure_context_per_db_type(DbTypes dbTypes) { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["ConnectionStrings:DefaultConnection"] = "invalid", ["DbType"] = dbTypes.ToString(), ["Migrate"] = "true", }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); if (dbTypes != DbTypes.InMemory) { Assert.ThrowsAny <Exception>(() => host.Start()); } }
public void Configure_should_load_provider_configuration() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["PrivateServerAuthentication:ApiUrl"] = "https://localhost:7443/api", ["Proxy"] = "true" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <Auth.SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <Auth.SchemeDefinition>().AsQueryable()).Verifiable(); var culturestoreMock = new Mock <IAdminStore <Culture> >(); culturestoreMock.Setup(m => m.GetAsync(It.IsAny <PageRequest>(), default)).ReturnsAsync(new PageResponse <Culture> { Items = Array.Empty <Culture>() }); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); services.AddTransient(p => culturestoreMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); host.Start(); storeMock.Verify(); }
public void Configure_should_configure_initial_data() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["ConnectionStrings:DefaultConnection"] = "Data source=./db.sql", ["DbType"] = "Sqlite", ["Migrate"] = "true", ["Seed"] = "true", ["SeedProvider"] = "true" }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); host.Start(); storeMock.Verify(); }
public void Configure_should_configure_data_protection_algorithms() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["DataProtectionOptions:AuthenticatedEncryptorConfiguration:EncryptionAlgorithm"] = EncryptionAlgorithm.AES_128_CBC.ToString(), }); var environementMock = new Mock <IWebHostEnvironment>(); var storeMock = new Mock <IDynamicProviderStore <SchemeDefinition> >(); storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty <SchemeDefinition>().AsQueryable()).Verifiable(); using var host = WebHost.CreateDefaultBuilder() .ConfigureServices(services => { services.AddTheIdServer(configuration); services.AddTransient(p => storeMock.Object); }) .Configure((context, builder) => builder.UseTheIdServer(context.HostingEnvironment, context.Configuration)) .UseSerilog((hostingContext, configuration) => configuration.ReadFrom.Configuration(hostingContext.Configuration)) .Build(); Assert.Null(host.Services.GetService <IXmlRepository>()); }
public void NewConfigurationRootMayBeBuiltFromExistingWithDuplicateKeys() { var configurationRoot = new ConfigurationManager(); configurationRoot.AddInMemoryCollection(new Dictionary <string, string> { { "keya:keyb", "valueA" }, }); configurationRoot.AddInMemoryCollection(new Dictionary <string, string> { { "KEYA:KEYB", "valueB" }, }); var newConfigurationRoot = new ConfigurationManager(); newConfigurationRoot.AddInMemoryCollection(configurationRoot.AsEnumerable()); Assert.Equal("valueB", newConfigurationRoot["keya:keyb"]); }
public void AutoUpdates() { var config = new ConfigurationManager(); config.AddInMemoryCollection(new Dictionary <string, string> { { "TestKey", "TestValue" }, }); Assert.Equal("TestValue", config["TestKey"]); }
public void TriggersReloadTokenOnSourceAddition() { var config = new ConfigurationManager(); var reloadToken = ((IConfiguration)config).GetReloadToken(); Assert.False(reloadToken.HasChanged); config.AddInMemoryCollection(new Dictionary <string, string> { { "TestKey", "TestValue" }, }); Assert.True(reloadToken.HasChanged); }
public static TestServer CreateTestServer( Action <IServiceCollection> configureServices = null, IEnumerable <KeyValuePair <string, string> > configurationOverrides = null) { var webHostBuilder = new WebHostBuilder() .UseEnvironment("Development") .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration)) .ConfigureServices((context, services) => { configureServices?.Invoke(services); var configurationManager = new ConfigurationManager(); #if DUENDE configurationManager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\..\src\Aguacongas.TheIdServer.Duende\appsettings.json")); #else configurationManager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\..\src\Aguacongas.TheIdServer.IS4\appsettings.json")); #endif configurationManager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"appsettings.Test.json"), true); if (configurationOverrides != null) { configurationManager.AddInMemoryCollection(configurationOverrides); } var isProxy = configurationManager.GetValue <bool>("Proxy"); var dbType = configurationManager.GetValue <DbTypes>("DbType"); services.AddTheIdServer(configurationManager); services.AddSingleton <TestUserService>() .AddMvc().AddApplicationPart(typeof(Config).Assembly); configureServices?.Invoke(services); }) .Configure((context, builder) => { builder.Use(async(context, next) => { var testService = context.RequestServices.GetRequiredService <TestUserService>(); context.User = testService.User; await next(); }); builder.UseTheIdServer(context.HostingEnvironment, context.Configuration); }); var testServer = new TestServer(webHostBuilder); return(testServer); }
public void DisposingConfigurationManagerCausesOnlySourceChangesToThrow() { var config = new ConfigurationManager { ["TestKey"] = "TestValue", }; config.Dispose(); Assert.Equal("TestValue", config["TestKey"]); config["TestKey"] = "TestValue2"; Assert.Equal("TestValue2", config["TestKey"]); Assert.Throws <ObjectDisposedException>(() => config.AddInMemoryCollection()); Assert.Throws <ObjectDisposedException>(() => ((IConfigurationBuilder)config).Sources.Clear()); }
public void KeyStartingWithColonMeansFirstSectionHasEmptyName() { // Arrange var dict = new Dictionary <string, string> { [":Key2"] = "value" }; var config = new ConfigurationManager(); config.AddInMemoryCollection(dict); // Act var children = config.GetChildren().ToArray(); // Assert Assert.Single(children); Assert.Equal(string.Empty, children.First().Key); Assert.Single(children.First().GetChildren()); Assert.Equal("Key2", children.First().GetChildren().First().Key); }
public void ConfigureServices_should_add_default_services() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["ConnectionStrings:DefaultConnection"] = Guid.NewGuid().ToString(), ["DbType"] = "InMemory" }); var services = new ServiceCollection(); services.AddTransient <IConfiguration>(p => configuration) .AddTheIdServer(configuration); var provider = services.BuildServiceProvider(); var schemeChangeSubscriber = provider.GetService <ISchemeChangeSubscriber>(); Assert.NotNull(schemeChangeSubscriber); Assert.Equal(typeof(SchemeChangeSubscriber <SchemeDefinition>), schemeChangeSubscriber.GetType()); }
public void ConfigureService_should_configure_mongodb_services() { var sessionMock = new Mock <IAsyncDocumentSession>(); var advancedMock = new Mock <IAsyncAdvancedSessionOperations>(); sessionMock.SetupGet(m => m.Advanced).Returns(advancedMock.Object); using var sut = new HostBuilder() .ConfigureServices((context, services) => { var configurationManager = new ConfigurationManager(); configurationManager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"appsettings.json")); configurationManager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"appsettings.Test.json"), true); configurationManager.AddInMemoryCollection(new Dictionary <string, string> { ["DbType"] = DbTypes.MongoDb.ToString(), ["ConnectionStrings:DefaultConnection"] = "mongodb://localhost/test", ["IdentityServer:Key:StorageKind"] = StorageKind.MongoDb.ToString(), ["DataProtectionOptions:StorageKind"] = StorageKind.MongoDb.ToString(), ["Seed"] = "false" }); services.AddTheIdServer(configurationManager); }).Build(); var provider = sut.Services; Assert.NotNull(provider.GetService <IAdminStore <ApiClaim> >()); var configureRotationOptions = provider.GetService <IConfigureOptions <KeyRotationOptions> >(); var rotationOptions = new KeyRotationOptions(); configureRotationOptions?.Configure(rotationOptions); Assert.IsType <MongoDb.MongoDbXmlRepository <MongoDb.KeyRotationKey> >(rotationOptions.XmlRepository); var configureManagementOptions = provider.GetService <IConfigureOptions <KeyManagementOptions> >(); var managementOptions = new KeyRotationOptions(); configureManagementOptions?.Configure(managementOptions); Assert.IsType <MongoDb.MongoDbXmlRepository <MongoDb.DataProtectionKey> >(managementOptions.XmlRepository); }
public void ConfigureServices_should_add_services_for_proxy() { var configuration = new ConfigurationManager(); configuration.AddInMemoryCollection(new Dictionary <string, string> { ["PrivateServerAuthentication:ApiUrl"] = "https://localhost:7443/api", ["Proxy"] = "true" }); var environementMock = new Mock <IWebHostEnvironment>(); var services = new ServiceCollection(); services.AddTransient <IConfiguration>(p => configuration); services.AddTheIdServer(configuration); var provider = services.BuildServiceProvider(); var schemeChangeSubscriber = provider.GetService <ISchemeChangeSubscriber>(); Assert.NotNull(schemeChangeSubscriber); Assert.Equal(typeof(SchemeChangeSubscriber <Auth.SchemeDefinition>), schemeChangeSubscriber.GetType()); }
public async Task ConfigureService_should_configure_proxy_services(bool disableStrictSll, string path, string otk, string token) { var sessionMock = new Mock <IAsyncDocumentSession>(); var advancedMock = new Mock <IAsyncAdvancedSessionOperations>(); sessionMock.SetupGet(m => m.Advanced).Returns(advancedMock.Object); using var sut = new HostBuilder() .ConfigureServices((context, services) => { var configurationMAnager = new ConfigurationManager(); configurationMAnager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"appsettings.json")); configurationMAnager.AddJsonFile(Path.Combine(Environment.CurrentDirectory, @"appsettings.Test.json"), true); configurationMAnager.AddInMemoryCollection(new Dictionary <string, string> { ["Proxy"] = "true", ["DisableStrictSsl"] = $"{disableStrictSll}", ["Seed"] = "false" }); services.AddTheIdServer(configurationMAnager); }).Build(); var provider = sut.Services; Assert.NotNull(provider.GetService <IProfileService>()); Assert.NotNull(provider.GetService <IAdminStore <Client> >()); var jwtBearerHandler = provider.GetService <JwtBearerHandler>(); Assert.NotNull(jwtBearerHandler); var mockHeader = new Mock <IHeaderDictionary>(); var queryCollection = new QueryCollection(new Dictionary <string, StringValues> { ["otk"] = otk }); var mockOneTimeTokenRetriver = new Mock <IRetrieveOneTimeToken>(); mockOneTimeTokenRetriver.Setup(m => m.GetOneTimeToken(It.IsAny <string>())).Returns(token); var requestServices = new ServiceCollection() .AddTransient(p => mockOneTimeTokenRetriver.Object) .BuildServiceProvider(); var mockHttRequest = new Mock <HttpRequest>(); mockHttRequest.SetupGet(m => m.Headers).Returns(mockHeader.Object); mockHttRequest.SetupGet(m => m.Query).Returns(queryCollection); mockHttRequest.SetupGet(m => m.Path).Returns(path); var mockHttpContext = new Mock <HttpContext>(); mockHttRequest.SetupGet(m => m.HttpContext).Returns(mockHttpContext.Object); mockHttpContext.SetupGet(m => m.Request).Returns(mockHttRequest.Object); mockHttpContext.SetupGet(m => m.RequestServices).Returns(requestServices); if (jwtBearerHandler != null) { await jwtBearerHandler.InitializeAsync(new AuthenticationScheme("Bearer", null, typeof(JwtBearerHandler)), mockHttpContext.Object).ConfigureAwait(false); await jwtBearerHandler.AuthenticateAsync().ConfigureAwait(false); } var oauthIntrospectionHandler = provider.GetService <OAuth2IntrospectionHandler>(); Assert.NotNull(oauthIntrospectionHandler); if (oauthIntrospectionHandler != null) { await oauthIntrospectionHandler.InitializeAsync(new AuthenticationScheme("introspection", null, typeof(OAuth2IntrospectionHandler)), mockHttpContext.Object).ConfigureAwait(false); await oauthIntrospectionHandler.AuthenticateAsync().ConfigureAwait(false); } }