public void Should_throw_exception_when_all_actions_are_not_configured() { //Arrange & Act var securityConfiguration = new SecurityConfiguration(policy => {}); //Assert Assert.Throws<ConfigurationErrorsException>(() => securityConfiguration.AssertAllActionsAreConfigured(new [] { GetType().Assembly })); }
public void Configuration() { MockSecurityConfigurationProvider provider = new MockSecurityConfigurationProvider(); SecurityConfiguration configuration = new SecurityConfiguration(); provider.Configuration = configuration; SecurityHelper.ConfigurationProvider = provider; Assert.AreSame(configuration, SecurityHelper.Configuration); }
public void Should_not_throw_exception_when_all_actions_are_configured() { //Arrange & Act var securityConfiguration = new SecurityConfiguration(policy => policy .ForAllControllers() .DenyAuthenticatedAccess() ); //Assert Assert.DoesNotThrow(() => securityConfiguration.AssertAllActionsAreConfigured(new [] { GetType().Assembly })); }
public void Should_not_throw_exception_when_all_actions_are_configured() { //Arrange & Act var assemblies = ( from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() where !(assembly is System.Reflection.Emit.AssemblyBuilder) && assembly.GetType().FullName != "System.Reflection.Emit.InternalAssemblyBuilder" && !assembly.GlobalAssemblyCache select assembly ).ToArray(); var securityConfiguration = new SecurityConfiguration(policy => policy .ForAllControllersInAssembly(assemblies) .DenyAuthenticatedAccess() ); //Assert Assert.DoesNotThrow(() => securityConfiguration.AssertAllActionsAreConfigured()); }
public RavenConfiguration(string resourceName, ResourceType resourceType, string customConfigPath = null) { ResourceName = resourceName; ResourceType = resourceType; _customConfigPath = customConfigPath; PathSettingBase <string> .ValidatePath(_customConfigPath); _configBuilder = new ConfigurationBuilder(); AddEnvironmentVariables(); AddJsonConfigurationVariables(customConfigPath); Settings = _configBuilder.Build(); Core = new CoreConfiguration(); Http = new HttpConfiguration(); Replication = new ReplicationConfiguration(); Cluster = new ClusterConfiguration(); Etl = new EtlConfiguration(); Storage = new StorageConfiguration(); Security = new SecurityConfiguration(); PerformanceHints = new PerformanceHintsConfiguration(); Indexing = new IndexingConfiguration(this); Monitoring = new MonitoringConfiguration(); Queries = new QueryConfiguration(); Patching = new PatchingConfiguration(); Logs = new LogsConfiguration(); Server = new ServerConfiguration(); Testing = new TestingConfiguration(); Databases = new DatabaseConfiguration(); Memory = new MemoryConfiguration(); Studio = new StudioConfiguration(); Licensing = new LicenseConfiguration(); Tombstones = new TombstoneConfiguration(); Subscriptions = new SubscriptionConfiguration(); TransactionMergerConfiguration = new TransactionMergerConfiguration(Storage.ForceUsing32BitsPager); }
public SqlServerFhirModel( SchemaInformation schemaInformation, ISearchParameterDefinitionManager searchParameterDefinitionManager, FilebasedSearchParameterStatusDataStore.Resolver filebasedRegistry, IOptions <SecurityConfiguration> securityConfiguration, ISqlConnectionStringProvider sqlConnectionStringProvider, IMediator mediator, ILogger <SqlServerFhirModel> logger) { EnsureArg.IsNotNull(schemaInformation, nameof(schemaInformation)); EnsureArg.IsNotNull(searchParameterDefinitionManager, nameof(searchParameterDefinitionManager)); EnsureArg.IsNotNull(filebasedRegistry, nameof(filebasedRegistry)); EnsureArg.IsNotNull(securityConfiguration?.Value, nameof(securityConfiguration)); EnsureArg.IsNotNull(sqlConnectionStringProvider, nameof(sqlConnectionStringProvider)); EnsureArg.IsNotNull(logger, nameof(logger)); _schemaInformation = schemaInformation; _searchParameterDefinitionManager = searchParameterDefinitionManager; _filebasedSearchParameterStatusDataStore = filebasedRegistry.Invoke(); _securityConfiguration = securityConfiguration.Value; _sqlConnectionStringProvider = sqlConnectionStringProvider; _mediator = mediator; _logger = logger; }
public void GivenUserHasProviderAssociations_WhenIExecuteDataSelector_ThenAssociationsIsProviderAssociationCount() { UserClientDataTable target = new UserClientDataTable(MockRequest, SecurityConfiguration); var providers = new List <Provider> { new Provider(), new Provider(), new Provider() }; User user = new User { UserRoles = new List <UserRole> { new UserRole { Role = new Role(), Providers = providers } } }; SecurityConfiguration.Expect(m => m.AdministratorEmailAddresses).Return(new string[] { "*****@*****.**" }); dynamic actual = target.DataSelector.Compile().Invoke(user); Assert.AreEqual(providers.Count, actual.Associations); }
private async Task <(SqlServerFhirStorageTestHelper testHelper, SchemaUpgradeRunner upgradeRunner)> SetupTestHelperAndCreateDatabase(string databaseName, int maxSchemaVersion, bool forceIncrementalSchemaUpgrade) { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; var searchService = Substitute.For <ISearchService>(); ISearchParameterDefinitionManager defManager = new SearchParameterDefinitionManager(ModelInfoProvider.Instance, Substitute.For <IMediator>(), () => searchService.CreateMockScope(), NullLogger <SearchParameterDefinitionManager> .Instance); FilebasedSearchParameterStatusDataStore statusStore = new FilebasedSearchParameterStatusDataStore(defManager, ModelInfoProvider.Instance); var schemaInformation = new SchemaInformation(SchemaVersionConstants.Min, maxSchemaVersion); var connectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = new SqlServerDataStoreConfiguration { ConnectionString = connectionString, Initialize = true, SchemaOptions = schemaOptions }; var sqlConnectionStringProvider = new DefaultSqlConnectionStringProvider(config); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; SqlServerFhirModel sqlServerFhirModel = new SqlServerFhirModel( schemaInformation, defManager, () => statusStore, Options.Create(securityConfiguration), sqlConnectionStringProvider, Substitute.For <IMediator>(), NullLogger <SqlServerFhirModel> .Instance); var sqlConnectionFactory = new DefaultSqlConnectionFactory(sqlConnectionStringProvider); var testHelper = new SqlServerFhirStorageTestHelper( initialConnectionString, MasterDatabaseName, sqlServerFhirModel, sqlConnectionFactory); var scriptProvider = new ScriptProvider <SchemaVersion>(); var baseScriptProvider = new BaseScriptProvider(); var mediator = Substitute.For <IMediator>(); var schemaManagerDataStore = new SchemaManagerDataStore(sqlConnectionFactory); var schemaUpgradeRunner = new SchemaUpgradeRunner( scriptProvider, baseScriptProvider, NullLogger <SchemaUpgradeRunner> .Instance, sqlConnectionFactory, schemaManagerDataStore); var schemaInitializer = new SchemaInitializer( config, schemaUpgradeRunner, schemaInformation, sqlConnectionFactory, sqlConnectionStringProvider, mediator, NullLogger <SchemaInitializer> .Instance); await testHelper.CreateAndInitializeDatabase( databaseName, maxSchemaVersion, forceIncrementalSchemaUpgrade, schemaInitializer); return(testHelper, schemaUpgradeRunner); }
public AadSmartOnFhirProxyFeatureFilterAttribute(IOptions <SecurityConfiguration> securityConfiguration) { _securityConfiguration = securityConfiguration.Value; }
private static void Because() { _securityConfiguration = new SecurityConfiguration(policy => { }); }
public void Should_return_the_current_configuration() { var securityConfiguration = new SecurityConfiguration(configuration => { configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse); configuration.IgnoreMissingConfiguration(); configuration.For<BlogController>(x => x.DeletePost(0)).DenyAnonymousAccess().RequireRole(UserRole.Owner, UserRole.Publisher); configuration.For<BlogController>(x => x.Index()).DenyAnonymousAccess(); }); // Act var whatIHave = securityConfiguration.WhatDoIHave(); // Assert Assert.That(whatIHave.Replace("\r\n", "|").Replace("\t", "%"), Is.EqualTo("Ignore missing configuration: True||------------------------------------------------------------------------------------|BlogController > DeletePost|%FluentSecurity.Policy.RequireRolePolicy (Owner or Publisher)|BlogController > Index|%FluentSecurity.Policy.DenyAnonymousAccessPolicy|------------------------------------------------------------------------------------")); }
/// <summary> /// 默认的构造函数,实例化一个新的OPC UA类 /// </summary> public OpcUaClient() { var certificateValidator = new CertificateValidator(); certificateValidator.CertificateValidation += (sender, eventArgs) => { if (ServiceResult.IsGood(eventArgs.Error)) { eventArgs.Accept = true; } else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted) { eventArgs.Accept = true; } else { LoggerService.Service.Warn("OpcClient", string.Format("Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo)); } }; SecurityConfiguration securityConfigurationcv = new SecurityConfiguration { AutoAcceptUntrustedCertificates = true, RejectSHA1SignedCertificates = false, MinimumCertificateKeySize = 1024, }; certificateValidator.Update(securityConfigurationcv); // Build the application configuration var configuration = new ApplicationConfiguration { ApplicationName = OpcUaName, ApplicationType = ApplicationType.Client, CertificateValidator = certificateValidator, ApplicationUri = "urn:SpiderOpcClient", //Kepp this syntax ProductUri = "SpiderOpcClient", ServerConfiguration = new ServerConfiguration { MaxSubscriptionCount = 100000, MaxMessageQueueSize = 1000000, MaxNotificationQueueSize = 1000000, MaxPublishRequestCount = 10000000, }, SecurityConfiguration = new SecurityConfiguration { AutoAcceptUntrustedCertificates = true, RejectSHA1SignedCertificates = false, MinimumCertificateKeySize = 1024, SuppressNonceValidationErrors = true, ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.X509Store, StorePath = "CurrentUser\\My", SubjectName = OpcUaName, }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.X509Store, StorePath = "CurrentUser\\Root", }, TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.X509Store, StorePath = "CurrentUser\\Root", } }, TransportQuotas = new TransportQuotas { OperationTimeout = 6000000, MaxStringLength = int.MaxValue, MaxByteStringLength = int.MaxValue, MaxArrayLength = 65535, MaxMessageSize = 419430400, MaxBufferSize = 65535, ChannelLifetime = -1, SecurityTokenLifetime = -1 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = -1, MinSubscriptionLifetime = -1, }, DisableHiResClock = true }; configuration.Validate(ApplicationType.Client); m_configuration = configuration; }
public SqlServerFhirStorageTestsFixture() { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _databaseName = $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}"; string masterConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = "master" }.ToString(); TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions }; var schemaInformation = new SchemaInformation(SchemaVersionConstants.Min, SchemaVersionConstants.Max); var scriptProvider = new ScriptProvider <SchemaVersion>(); var schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, config, NullLogger <SchemaUpgradeRunner> .Instance); _schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, NullLogger <SchemaInitializer> .Instance); var searchParameterDefinitionManager = Substitute.For <ISearchParameterDefinitionManager>(); searchParameterDefinitionManager.AllSearchParameters.Returns(new[] { new SearchParameter { Name = SearchParameterNames.Id, Type = SearchParamType.Token, Url = SearchParameterNames.IdUri.ToString() }.ToInfo(), new SearchParameter { Name = SearchParameterNames.LastUpdated, Type = SearchParamType.Date, Url = SearchParameterNames.LastUpdatedUri.ToString() }.ToInfo(), }); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel(config, _schemaInitializer, searchParameterDefinitionManager, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <ResourceMetadata> >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(new SupportedSearchParameterDefinitionManager(searchParameterDefinitionManager)); SqlTransactionHandler = new SqlTransactionHandler(); SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(config, SqlTransactionHandler, new SqlCommandWrapperFactory()); _fhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGenerator, Options.Create(new CoreFeatureConfiguration()), SqlConnectionWrapperFactory, NullLogger <SqlServerFhirDataStore> .Instance, schemaInformation); _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(TestConnectionString, initialConnectionString, masterConnectionString, sqlServerFhirModel); }
private static void Because() { _securityConfiguration = new SecurityConfiguration(policy => policy.IgnoreMissingConfiguration()); }
protected MatchBoxControllerBase(SecurityConfiguration securityConfig) : base() { SystemConfiguration = securityConfig; }
public static new void StartTheSystem(SecurityConfiguration configuration) { SecurityContext.StartTheSystem(configuration); _generalContext = new SecurityContextForConcurrencyTests(SystemUser); }
/// <summary> /// Main /// </summary> /// <param name="args"></param> public static void Main(string[] args) { Console.WriteLine("Starting LightLDS - The lightweight OPC UA Local Discovery Server"); ApplicationInstance application = new ApplicationInstance(); try { var applicationConfiguration = new ApplicationConfiguration(); applicationConfiguration.ApplicationName = "Light OPC UA Local Discovery Server"; applicationConfiguration.ApplicationUri = "urn:localhost:K47S:LocalDiscoveryServer"; applicationConfiguration.ProductUri = "http://K47S/LocalDiscoveryServer"; applicationConfiguration.ApplicationType = ApplicationType.DiscoveryServer; var securityConfiguration = new SecurityConfiguration(); securityConfiguration.ApplicationCertificate = new CertificateIdentifier() { StoreType = @"Directory", StorePath = @"%CommonApplicationData%/LightLDS/PKI/own", SubjectName = "CN=Local Discovery Server, O=K47S, DC=localhost", }; securityConfiguration.TrustedIssuerCertificates = new CertificateTrustList() { StoreType = @"Directory", StorePath = @"%CommonApplicationData%/LightLDS/PKI/issuers", }; securityConfiguration.TrustedPeerCertificates = new CertificateTrustList() { StoreType = @"Directory", StorePath = @"%CommonApplicationData%/LightLDS/PKI/trusted", }; securityConfiguration.RejectedCertificateStore = new CertificateTrustList() { StoreType = @"Directory", StorePath = @"%CommonApplicationData%/LightLDS/PKI/rejected", }; securityConfiguration.AutoAcceptUntrustedCertificates = true; securityConfiguration.RejectSHA1SignedCertificates = false; securityConfiguration.MinimumCertificateKeySize = 1024; applicationConfiguration.SecurityConfiguration = securityConfiguration; var serverConfiguration = new ServerConfiguration(); serverConfiguration.BaseAddresses = new StringCollection(new List <string>() { "opc.tcp://localhost:4840" }); serverConfiguration.SecurityPolicies = new ServerSecurityPolicyCollection(new List <ServerSecurityPolicy>() { new ServerSecurityPolicy() { SecurityMode = MessageSecurityMode.None, SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None", } }); serverConfiguration.UserTokenPolicies = new UserTokenPolicyCollection(new List <UserTokenPolicy>() { new UserTokenPolicy() { TokenType = UserTokenType.Anonymous, SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None" } }); serverConfiguration.DiagnosticsEnabled = true; serverConfiguration.MaxSessionCount = 100; serverConfiguration.MinSessionTimeout = 10000; serverConfiguration.MaxSessionTimeout = 3600000; serverConfiguration.MaxBrowseContinuationPoints = 10; serverConfiguration.MaxQueryContinuationPoints = 10; serverConfiguration.MaxHistoryContinuationPoints = 100; serverConfiguration.MaxRequestAge = 600000; serverConfiguration.MinPublishingInterval = 100; serverConfiguration.MaxPublishingInterval = 3600000; serverConfiguration.PublishingResolution = 100; serverConfiguration.MaxSubscriptionLifetime = 3600000; serverConfiguration.MaxMessageQueueSize = 100; serverConfiguration.MaxNotificationQueueSize = 100; serverConfiguration.MaxNotificationsPerPublish = 1000; serverConfiguration.MinMetadataSamplingInterval = 1000; applicationConfiguration.ServerConfiguration = serverConfiguration; var transportQuotaConfig = new TransportQuotas(); applicationConfiguration.TransportQuotas = transportQuotaConfig; var traceConfiguration = new TraceConfiguration(); traceConfiguration.OutputFilePath = "%CommonApplicationData%/LightLDS/Logs/LocalDiscoveryServer.log.txt"; traceConfiguration.DeleteOnLoad = true; traceConfiguration.TraceMasks = 0x7FFFFFFF; applicationConfiguration.TraceConfiguration = traceConfiguration; application.ApplicationConfiguration = applicationConfiguration; application.ApplicationConfiguration.Validate(ApplicationType.Server); // check the application certificate. application.CheckApplicationInstanceCertificate(false, 0).Wait(); // start the server. var server = new DiscoveryServerInstance(); application.Start(server).Wait(); Console.WriteLine("LightLDS running. Press ENTER to exit."); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadLine(); }
/// <summary> /// Initializes a new instance of the <see cref="AntiForgeryMiddleware" /> class. /// </summary> /// <param name="next">The next.</param> /// <param name="antiforgery">The antiforgery.</param> /// <param name="config">The configuration.</param> public AntiForgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery, IConfiguration config) { _antiAntiforgery = antiforgery; _next = next; _securityConfiguration = config.GetSection(SecurityConfigurationSection).Get <SecurityConfiguration>(); }
public SqlServerFhirStorageTestsFixture() { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalDatabase.DefaultConnectionString; _databaseName = $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}"; _masterConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = "master" }.ToString(); TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); using (var connection = new SqlConnection(_masterConnectionString)) { connection.Open(); using (SqlCommand command = connection.CreateCommand()) { command.CommandTimeout = 600; command.CommandText = $"CREATE DATABASE {_databaseName}"; command.ExecuteNonQuery(); } } var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true }; var schemaUpgradeRunner = new SchemaUpgradeRunner(config); var schemaInformation = new SchemaInformation(); var schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, NullLogger <SchemaInitializer> .Instance); schemaInitializer.Start(); var searchParameterDefinitionManager = Substitute.For <ISearchParameterDefinitionManager>(); searchParameterDefinitionManager.AllSearchParameters.Returns(new[] { new SearchParameter { Id = SearchParameterNames.Id, Url = SearchParameterNames.IdUri.ToString() }, new SearchParameter { Id = SearchParameterNames.LastUpdated, Url = SearchParameterNames.LastUpdatedUri.ToString() }, }); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel(config, schemaInformation, searchParameterDefinitionManager, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGenerator = serviceProvider.GetRequiredService <V1.UpsertResourceTvpGenerator <ResourceMetadata> >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(searchParameterDefinitionManager); _fhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGenerator, NullLogger <SqlServerFhirDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(TestConnectionString); }
public SqlServerFhirStorageTestsFixture() { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _databaseName = $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}"; TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions }; var schemaInformation = new SchemaInformation(SchemaVersionConstants.Min, SchemaVersionConstants.Max); var scriptProvider = new ScriptProvider <SchemaVersion>(); var baseScriptProvider = new BaseScriptProvider(); var mediator = Substitute.For <IMediator>(); var sqlConnectionFactory = new DefaultSqlConnectionFactory(config); var schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, baseScriptProvider, mediator, NullLogger <SchemaUpgradeRunner> .Instance, sqlConnectionFactory); _schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, sqlConnectionFactory, NullLogger <SchemaInitializer> .Instance); var searchParameterDefinitionManager = new SearchParameterDefinitionManager(ModelInfoProvider.Instance); _filebasedSearchParameterStatusDataStore = new FilebasedSearchParameterStatusDataStore(searchParameterDefinitionManager, ModelInfoProvider.Instance); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel( config, schemaInformation, searchParameterDefinitionManager, () => _filebasedSearchParameterStatusDataStore, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <ResourceMetadata> >(); var upsertSearchParamsTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertSearchParamsTvpGenerator <List <ResourceSearchParameterStatus> > >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(new SupportedSearchParameterDefinitionManager(searchParameterDefinitionManager)); SqlTransactionHandler = new SqlTransactionHandler(); SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(SqlTransactionHandler, new SqlCommandWrapperFactory(), sqlConnectionFactory); SqlServerSearchParameterStatusDataStore = new SqlServerSearchParameterStatusDataStore( () => SqlConnectionWrapperFactory.CreateMockScope(), upsertSearchParamsTvpGenerator, () => _filebasedSearchParameterStatusDataStore, schemaInformation); _fhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGenerator, Options.Create(new CoreFeatureConfiguration()), SqlConnectionWrapperFactory, NullLogger <SqlServerFhirDataStore> .Instance, schemaInformation); _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(initialConnectionString, MasterDatabaseName, searchParameterDefinitionManager, sqlServerFhirModel, sqlConnectionFactory); }
// C'tor public GcnHeaderSecurityMiddleware(RequestDelegate next, IOptions <SecurityConfiguration> config) { _next = next; _config = config.Value; }
/// <summary> /// Updates the XML document with the new configuration information. /// </summary> private static void UpdateDocument(XmlElement element, SecuredApplication application) { for (XmlNode node = element.FirstChild; node != null; node = node.NextSibling) { if (node.Name == "ApplicationName" && node.NamespaceURI == Namespaces.OpcUaConfig) { node.InnerText = application.ApplicationName; continue; } if (node.Name == "ApplicationUri" && node.NamespaceURI == Namespaces.OpcUaConfig) { node.InnerText = application.ApplicationUri; continue; } if (node.Name == "SecurityConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig) { SecurityConfiguration security = (SecurityConfiguration)GetObject(typeof(SecurityConfiguration), node); if (application.ApplicationCertificate != null) { security.ApplicationCertificate = SecuredApplication.FromCertificateIdentifier(application.ApplicationCertificate); } security.TrustedIssuerCertificates = SecuredApplication.FromCertificateStoreIdentifierToTrustList(application .IssuerCertificateStore); security.TrustedIssuerCertificates.TrustedCertificates = SecuredApplication.FromCertificateList(application.IssuerCertificates); security.TrustedPeerCertificates = SecuredApplication.FromCertificateStoreIdentifierToTrustList( application.TrustedCertificateStore); security.TrustedPeerCertificates.TrustedCertificates = SecuredApplication.FromCertificateList(application.TrustedCertificates); security.RejectedCertificateStore = SecuredApplication.FromCertificateStoreIdentifier(application.RejectedCertificatesStore); node.InnerXml = SetObject(typeof(SecurityConfiguration), security); continue; } if (node.Name == "ServerConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig) { ServerConfiguration configuration = (ServerConfiguration)GetObject(typeof(ServerConfiguration), node); SecuredApplication.FromListOfBaseAddresses(configuration, application.BaseAddresses); configuration.SecurityPolicies = SecuredApplication.FromListOfSecurityProfiles(application.SecurityProfiles); node.InnerXml = SetObject(typeof(ServerConfiguration), configuration); continue; } else if (node.Name == "DiscoveryServerConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig) { DiscoveryServerConfiguration configuration = (DiscoveryServerConfiguration)GetObject(typeof(DiscoveryServerConfiguration), node); SecuredApplication.FromListOfBaseAddresses(configuration, application.BaseAddresses); configuration.SecurityPolicies = SecuredApplication.FromListOfSecurityProfiles(application.SecurityProfiles); node.InnerXml = SetObject(typeof(DiscoveryServerConfiguration), configuration); continue; } } }
static void callMethod() { EndpointConfiguration ec = new EndpointConfiguration(); EndpointDescription endpointDescription = new EndpointDescription("opc.tcp://localhost:58710/PCoUaServer"); configuredEndpoint = new ConfiguredEndpoint(new ConfiguredEndpointCollection(), endpointDescription); configuredEndpoint.Configuration.UseBinaryEncoding = true; configuredEndpoint.Description.UserIdentityTokens.Add(new UserTokenPolicy(UserTokenType.Anonymous)); applicationConfiguration = new ApplicationConfiguration(); applicationConfiguration.ApplicationType = ApplicationType.Client; applicationConfiguration.ApplicationName = "SAPClientSession"; applicationConfiguration.ApplicationUri = "SAPClientSession"; SecurityConfiguration secConfig = new SecurityConfiguration(); secConfig.ApplicationCertificate = GetPCoDefaultCertificate(); applicationConfiguration.SecurityConfiguration = secConfig; TransportQuotas transportQuotas = new TransportQuotas(); applicationConfiguration.TransportQuotas = transportQuotas; ClientConfiguration clientConfiguration = new ClientConfiguration(); applicationConfiguration.ClientConfiguration = clientConfiguration; applicationConfiguration.Validate(ApplicationType.Client); CertificateValidationOptions certOptions = applicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.ValidationOptions; certOptions |= CertificateValidationOptions.SuppressCertificateExpired; certOptions |= CertificateValidationOptions.SuppressHostNameInvalid; securelyUpdateEndpointConfiguration(configuredEndpoint, applicationConfiguration); applicationConfiguration.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; clientSession = Session.Create( applicationConfiguration, configuredEndpoint, false, false, sessionName, sessionTimeout, identity, null, null); clientSession.ReturnDiagnostics = DiagnosticsMasks.All; clientSession.KeepAliveInterval = 2 * 1000; try { int maxNodesPerReadRuntimeInformation = Convert.ToInt32(clientSession.ReadValue(Opc.Ua.VariableIds.Server_ServerCapabilities_OperationLimits_MaxNodesPerRead).Value); //if (tracer.Switch.ShouldTrace(TraceEventType.Verbose)) { String message = String.Format("Retrieved operation limits for reading ({0}) from server", maxNodesPerReadRuntimeInformation); //TraceUtility.LogData(tracer, TraceUtility.EventId.E2718, TraceEventType.Verbose, message); } } catch (Exception) { // the value is not supplied or an error occured. { String message = String.Format("Could not retrieve operation limits for reading from server"); } } //NodeId nodeiD = clientSession.ReadNode(); var v11 = clientSession.Call((NodeId)("ns=2;s=348259fa-527e-4d5e-bde1-f5e1ccf01d61"), (NodeId)("ns=2;s=aef01ad4-3fe3-4836-83d0-cc808735f530"), new object[] { }); //BrowseResultCollection browseResultCollection; //DiagnosticInfoCollection diagnosticInfos; //NodeId currentNode = FindCurrentNode(null, clientSession, configuredEndpoint); //uint nodeClassMask = (uint)(NodeClass.Object | NodeClass.Method); //BrowseDescriptionCollection nodesToBrowse = PrepareBrowseDescriptionCollection(currentNode, nodeClassMask); //clientSession.Browse( // null, // null, // 100, // nodesToBrowse, // out browseResultCollection, // out diagnosticInfos); //var app_Base_To_method = clientSession.ReadNode((NodeId)(browseResultCollection[0].References[1].NodeId.ToString())); //ClientBase.ValidateResponse(browseResultCollection, nodesToBrowse); //ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); //ReferenceDescriptionCollection references; ////int resultLength = 0; //foreach (BrowseResult br in browseResultCollection) //{ // /// TODO: Store the continuation point as member of UaBrowser (new class) and // /// use it when we are called with BrowseNext mode. // byte[] continuationPoint = br.ContinuationPoint; // while (continuationPoint != null) // { // byte[] revisedContinuationPoint; // ResponseHeader rc = clientSession.BrowseNext( // null, // false, // continuationPoint, // out revisedContinuationPoint, // out references); // br.References.AddRange(references); // //resultLength += br.References.Count; // if (br.References.Count >= 100) // { // //int removeCount = br.References.Count - maxRows; // br.References.RemoveRange((int)100, (int)br.References.Count - (int)100); // continuationPoint = revisedContinuationPoint; // if (continuationPoint != null) // { // // release continuation point on server // rc = clientSession.BrowseNext( // null, // true, // <- release cp // continuationPoint, // out revisedContinuationPoint, // out references); // } // break; // } // continuationPoint = revisedContinuationPoint; // } //} ////ns=2;s=a72e725d-6be7-4a17-bcd4-0be67b6cbfbe ////browseResultCollection[0].References[1].NodeId; //var vrere = clientSession.ReadNode((NodeId)("ns=2;s=50bcabac-623b-43ea-8f69-17b12d533166")); //nodesToBrowse = PrepareBrowseDescriptionCollection // ((NodeId)(browseResultCollection[0].References[1].NodeId.ToString()), nodeClassMask); //clientSession.Browse( // null, // null, // 100, // nodesToBrowse, // out browseResultCollection, // out diagnosticInfos); //var application_method = clientSession.ReadNode((NodeId)(browseResultCollection[1].References[0].NodeId.ToString())); //var v1 = clientSession.FetchReferences((NodeId)(browseResultCollection[1].References[0].NodeId.ToString())); ////var v2 = clientSession.ReadValue((NodeId)(browseResultCollection[1].References[0].NodeId.ToString())); //nodesToBrowse = PrepareBrowseDescriptionCollection // ((NodeId)(browseResultCollection[1].References[0].NodeId.ToString()), nodeClassMask); //clientSession.Browse(null, null, 100, nodesToBrowse, out browseResultCollection, out diagnosticInfos); //var v = clientSession.ReadNode((NodeId)(browseResultCollection[5].References[0].NodeId.ToString())); //v1 = clientSession.FetchReferences((NodeId)(browseResultCollection[5].References[0].NodeId.ToString())); ////v2 = clientSession.ReadValue((NodeId)(browseResultCollection[5].References[0].NodeId.ToString())); ////TypeInfo.GetSystemType(dataType, clientSession.Factory); //nodeClassMask = (uint)(NodeClass.Object | NodeClass.Method | NodeClass.View | // NodeClass.VariableType | NodeClass.Variable | NodeClass.ObjectType); //nodesToBrowse = PrepareBrowseDescriptionCollection // ((NodeId)(browseResultCollection[5].References[0].NodeId.ToString()), nodeClassMask); //var v5 = clientSession.ReadNode((NodeId)(browseResultCollection[5].References[0].NodeId.ToString())); //clientSession.Browse(null, null, 100, nodesToBrowse, out browseResultCollection, out diagnosticInfos); //BrowsePathCollection pathsToArgs = new BrowsePathCollection(); //BrowsePath pathToInputArgs = new BrowsePath(); //pathToInputArgs.StartingNode = application_method.NodeId; //pathToInputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("InputArguments")); //pathsToArgs.Add(pathToInputArgs); //BrowsePath pathToOutputArgs = new BrowsePath(); //pathToOutputArgs.StartingNode = application_method.NodeId; //pathToOutputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("OutputArguments")); //pathsToArgs.Add(pathToOutputArgs); //BrowsePathResultCollection results = null; //// Get the nodeId of the input argument //ResponseHeader responseHeader = clientSession.TranslateBrowsePathsToNodeIds( // null, // pathsToArgs, // out results, // out diagnosticInfos // ); //ArgumentCollection[] arguments = new ArgumentCollection[2]; //for (int i = 0; i < 2; i++) //{ // arguments[i] = new ArgumentCollection(); // foreach (BrowsePathTarget bptarget in results[i].Targets) // { // DataValueCollection readResults = null; // ReadValueId nodeToRead = new ReadValueId(); // nodeToRead.NodeId = (NodeId)bptarget.TargetId; // nodeToRead.AttributeId = Attributes.Value; // ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); // nodesToRead.Add(nodeToRead); // DiagnosticInfoCollection readDiagnoistcInfos = null; // clientSession.Read( // null, // 0, // TimestampsToReturn.Neither, // nodesToRead, // out readResults, // out readDiagnoistcInfos // ); // ExtensionObject[] exts = (ExtensionObject[])readResults[0].Value; // for (int j = 0; j < exts.Length; ++j) // { // ExtensionObject ext = exts[j]; // arguments[i].Add((Argument)ext.Body); // } // } //} // establish keep-alive //clientSession.KeepAlive += new KeepAliveEventHandler(clientSession_KeepAlive); }
/// <summary> /// Starts the security subsystem using the passed configuration. /// The method prepares and memorizes the main components for /// creating SecurityContext instances in a fastest possible way. /// The main components are global objects: /// ISecurityDataProvider instance, IMessageProvider instance and SecurityCache instance. /// </summary> public static new void StartTheSystem(SecurityConfiguration configuration) { SecurityContext.StartTheSystem(configuration); _generalContext = new SnSecurityContext(new SystemUser(null)); }
public void Should_return_the_current_configuration() { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var fullFilePath = Path.Combine(baseDirectory, "TestData", "DiagnosticsOutputExample.txt"); var expectedOutput = File.ReadAllText(fullFilePath); var securityConfiguration = new SecurityConfiguration(configuration => { configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse); configuration.IgnoreMissingConfiguration(); configuration.For<BlogController>(x => x.DeletePost(0)).DenyAnonymousAccess().RequireRole(UserRole.Owner, UserRole.Publisher); configuration.For<BlogController>(x => x.Index()).DenyAnonymousAccess(); }); SecurityConfigurator.SetConfiguration(securityConfiguration); // Act var whatIHave = securityConfiguration.WhatDoIHave(); // Assert Assert.That(whatIHave, Is.EqualTo(expectedOutput)); }
private bool AddTrustListToStore(SecurityConfiguration config, TrustListDataType trustList) { TrustListMasks masks = (TrustListMasks)trustList.SpecifiedLists; X509Certificate2Collection issuerCertificates = null; List <X509CRL> issuerCrls = null; X509Certificate2Collection trustedCertificates = null; List <X509CRL> trustedCrls = null; // test integrity of all CRLs if ((masks & TrustListMasks.IssuerCertificates) != 0) { issuerCertificates = new X509Certificate2Collection(); foreach (var cert in trustList.IssuerCertificates) { issuerCertificates.Add(new X509Certificate2(cert)); } } if ((masks & TrustListMasks.IssuerCrls) != 0) { issuerCrls = new List <X509CRL>(); foreach (var crl in trustList.IssuerCrls) { issuerCrls.Add(new X509CRL(crl)); } } if ((masks & TrustListMasks.TrustedCertificates) != 0) { trustedCertificates = new X509Certificate2Collection(); foreach (var cert in trustList.TrustedCertificates) { trustedCertificates.Add(new X509Certificate2(cert)); } } if ((masks & TrustListMasks.TrustedCrls) != 0) { trustedCrls = new List <X509CRL>(); foreach (var crl in trustList.TrustedCrls) { trustedCrls.Add(new X509CRL(crl)); } } // update store // test integrity of all CRLs TrustListMasks updateMasks = TrustListMasks.None; if ((masks & TrustListMasks.IssuerCertificates) != 0) { if (UpdateStoreCertificates(config.TrustedIssuerCertificates.StorePath, issuerCertificates)) { updateMasks |= TrustListMasks.IssuerCertificates; } } if ((masks & TrustListMasks.IssuerCrls) != 0) { if (UpdateStoreCrls(config.TrustedIssuerCertificates.StorePath, issuerCrls)) { updateMasks |= TrustListMasks.IssuerCrls; } } if ((masks & TrustListMasks.TrustedCertificates) != 0) { if (UpdateStoreCertificates(config.TrustedPeerCertificates.StorePath, trustedCertificates)) { updateMasks |= TrustListMasks.TrustedCertificates; } } if ((masks & TrustListMasks.TrustedCrls) != 0) { if (UpdateStoreCrls(config.TrustedPeerCertificates.StorePath, trustedCrls)) { updateMasks |= TrustListMasks.TrustedCrls; } } return(masks == updateMasks); }
public GroupsController(SecurityConfiguration config, MatchBoxDbContext dbContext, IMapper mapper) : base(config, dbContext, mapper) { }
internal SqlServerFhirStorageTestsFixture(int maximumSupportedSchemaVersion, string databaseName, IOptions <CoreFeatureConfiguration> coreFeatures = null) { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _maximumSupportedSchemaVersion = maximumSupportedSchemaVersion; _databaseName = databaseName; TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = Options.Create(new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions, StatementTimeout = TimeSpan.FromMinutes(10) }); SchemaInformation = new SchemaInformation(SchemaVersionConstants.Min, maximumSupportedSchemaVersion); var scriptProvider = new ScriptProvider <SchemaVersion>(); var baseScriptProvider = new BaseScriptProvider(); var mediator = Substitute.For <IMediator>(); var sqlSortingValidator = new SqlServerSortingValidator(SchemaInformation); var sqlConnectionStringProvider = new DefaultSqlConnectionStringProvider(config); SqlConnectionFactory = new DefaultSqlConnectionFactory(sqlConnectionStringProvider); var schemaManagerDataStore = new SchemaManagerDataStore(SqlConnectionFactory, config, NullLogger <SchemaManagerDataStore> .Instance); _schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, baseScriptProvider, NullLogger <SchemaUpgradeRunner> .Instance, SqlConnectionFactory, schemaManagerDataStore); _schemaInitializer = new SchemaInitializer(config, schemaManagerDataStore, _schemaUpgradeRunner, SchemaInformation, SqlConnectionFactory, sqlConnectionStringProvider, mediator, NullLogger <SchemaInitializer> .Instance); _searchParameterDefinitionManager = new SearchParameterDefinitionManager(ModelInfoProvider.Instance, _mediator, () => _searchService.CreateMockScope(), NullLogger <SearchParameterDefinitionManager> .Instance); _searchParameterDefinitionManager.StartAsync(CancellationToken.None); _filebasedSearchParameterStatusDataStore = new FilebasedSearchParameterStatusDataStore(_searchParameterDefinitionManager, ModelInfoProvider.Instance); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel( SchemaInformation, _searchParameterDefinitionManager, () => _filebasedSearchParameterStatusDataStore, Options.Create(securityConfiguration), SqlConnectionFactory, Substitute.For <IMediator>(), NullLogger <SqlServerFhirModel> .Instance); SqlServerFhirModel = sqlServerFhirModel; var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); serviceCollection.AddSingleton <ISqlServerFhirModel>(sqlServerFhirModel); serviceCollection.AddSingleton(searchParameterToSearchValueTypeMap); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGeneratorV6 = serviceProvider.GetRequiredService <V6.UpsertResourceTvpGenerator <ResourceMetadata> >(); var upsertResourceTvpGeneratorV7 = serviceProvider.GetRequiredService <V7.UpsertResourceTvpGenerator <ResourceMetadata> >(); var upsertResourceTvpGeneratorV13 = serviceProvider.GetRequiredService <V13.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var upsertResourceTvpGeneratorV17 = serviceProvider.GetRequiredService <V17.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var upsertResourceTvpGeneratorVLatest = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var reindexResourceTvpGeneratorV17 = serviceProvider.GetRequiredService <V17.ReindexResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var bulkReindexResourceTvpGeneratorV17 = serviceProvider.GetRequiredService <V17.BulkReindexResourcesTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var reindexResourceTvpGeneratorVLatest = serviceProvider.GetRequiredService <VLatest.ReindexResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var bulkReindexResourceTvpGeneratorVLatest = serviceProvider.GetRequiredService <VLatest.BulkReindexResourcesTvpGenerator <IReadOnlyList <ResourceWrapper> > >(); var upsertSearchParamsTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertSearchParamsTvpGenerator <List <ResourceSearchParameterStatus> > >(); _supportedSearchParameterDefinitionManager = new SupportedSearchParameterDefinitionManager(_searchParameterDefinitionManager); SqlTransactionHandler = new SqlTransactionHandler(); SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(SqlTransactionHandler, new SqlCommandWrapperFactory(), SqlConnectionFactory); SqlServerSearchParameterStatusDataStore = new SqlServerSearchParameterStatusDataStore( () => SqlConnectionWrapperFactory.CreateMockScope(), upsertSearchParamsTvpGenerator, () => _filebasedSearchParameterStatusDataStore, SchemaInformation, sqlSortingValidator, sqlServerFhirModel, _searchParameterDefinitionManager); IOptions <CoreFeatureConfiguration> options = coreFeatures ?? Options.Create(new CoreFeatureConfiguration()); _fhirDataStore = new SqlServerFhirDataStore( sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGeneratorV6, upsertResourceTvpGeneratorV7, upsertResourceTvpGeneratorV13, upsertResourceTvpGeneratorV17, upsertResourceTvpGeneratorVLatest, reindexResourceTvpGeneratorV17, reindexResourceTvpGeneratorVLatest, bulkReindexResourceTvpGeneratorV17, bulkReindexResourceTvpGeneratorVLatest, options, SqlConnectionWrapperFactory, new CompressedRawResourceConverter(), NullLogger <SqlServerFhirDataStore> .Instance, SchemaInformation); _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance); _fhirRequestContextAccessor.RequestContext.CorrelationId.Returns(Guid.NewGuid().ToString()); _fhirRequestContextAccessor.RequestContext.RouteName.Returns("routeName"); var searchableSearchParameterDefinitionManager = new SearchableSearchParameterDefinitionManager(_searchParameterDefinitionManager, _fhirRequestContextAccessor); var searchParameterExpressionParser = new SearchParameterExpressionParser(new ReferenceSearchValueParser(_fhirRequestContextAccessor)); var expressionParser = new ExpressionParser(() => searchableSearchParameterDefinitionManager, searchParameterExpressionParser); var searchOptionsFactory = new SearchOptionsFactory( expressionParser, () => searchableSearchParameterDefinitionManager, options, _fhirRequestContextAccessor, sqlSortingValidator, NullLogger <SearchOptionsFactory> .Instance); var searchParamTableExpressionQueryGeneratorFactory = new SearchParamTableExpressionQueryGeneratorFactory(searchParameterToSearchValueTypeMap); var sqlRootExpressionRewriter = new SqlRootExpressionRewriter(searchParamTableExpressionQueryGeneratorFactory); var chainFlatteningRewriter = new ChainFlatteningRewriter(searchParamTableExpressionQueryGeneratorFactory); var sortRewriter = new SortRewriter(searchParamTableExpressionQueryGeneratorFactory); var partitionEliminationRewriter = new PartitionEliminationRewriter(sqlServerFhirModel, SchemaInformation, () => searchableSearchParameterDefinitionManager); _searchService = new SqlServerSearchService( searchOptionsFactory, _fhirDataStore, sqlServerFhirModel, sqlRootExpressionRewriter, chainFlatteningRewriter, sortRewriter, partitionEliminationRewriter, SqlConnectionWrapperFactory, SchemaInformation, _fhirRequestContextAccessor, new CompressedRawResourceConverter(), NullLogger <SqlServerSearchService> .Instance); ISearchParameterSupportResolver searchParameterSupportResolver = Substitute.For <ISearchParameterSupportResolver>(); searchParameterSupportResolver.IsSearchParameterSupported(Arg.Any <SearchParameterInfo>()).Returns((true, false)); _searchParameterStatusManager = new SearchParameterStatusManager( SqlServerSearchParameterStatusDataStore, _searchParameterDefinitionManager, searchParameterSupportResolver, mediator, NullLogger <SearchParameterStatusManager> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(initialConnectionString, MasterDatabaseName, sqlServerFhirModel, SqlConnectionFactory); }
public static new void StartTheSystem(SecurityConfiguration configuration) { SecurityContext.StartTheSystem(configuration); _generalContext = new TestSecurityContext(SystemUser); }
public Security(SecurityConfiguration config) { _config = config; }
public CachedUserRepository(IDependencyResolver dependencyResolver, ICache cache, ICacheHelper cacheHelper, SecurityConfiguration configuration) : base(dependencyResolver, cache, cacheHelper) { _configuration = configuration; }
public SecurityModule(DicomServerConfiguration dicomServerConfiguration) { EnsureArg.IsNotNull(dicomServerConfiguration, nameof(dicomServerConfiguration)); _securityConfiguration = dicomServerConfiguration.Security; }
internal static bool CertHasKnownIssuer(X509Certificate2 userCertificate, X509Certificate2 knownCertificate, SecurityConfiguration securityConfiguration, out string issuerPinningHash) { issuerPinningHash = null; X509Certificate2 issuerCertificate = null; var userChain = new X509Chain(); // we are not disabling certificate downloads because this method is checking public key pinning hashes // in order to do that properly it needs to be able to verify the chain by download the certificates // userChain.ChainPolicy.DisableCertificateDownloads = true; var knownCertChain = new X509Chain(); // we are not disabling certificate downloads because this method is checking public key pinning hashes // in order to do that properly it needs to be able to verify the chain by download the certificates //knownCertChain.ChainPolicy.DisableCertificateDownloads = true; try { userChain.Build(userCertificate); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info($"Cannot validate new client certificate '{userCertificate.FriendlyName} {userCertificate.Thumbprint}', failed to build the chain.", e); } return(false); } try { issuerCertificate = userChain.ChainElements.Count > 1 ? userChain.ChainElements[1].Certificate : userChain.ChainElements[0].Certificate; issuerPinningHash = issuerCertificate.GetPublicKeyPinningHash(); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info($"Cannot extract pinning hash from the client certificate's issuer '{issuerCertificate?.FriendlyName} {issuerCertificate?.Thumbprint}'.", e); } return(false); } var wellKnown = securityConfiguration.WellKnownIssuerHashes; if (wellKnown != null && wellKnown.Contains(issuerPinningHash, StringComparer.Ordinal)) // Case sensitive, base64 { return(true); } try { knownCertChain.Build(knownCertificate); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info($"Cannot validate new client certificate '{userCertificate.FriendlyName} {userCertificate.Thumbprint}'. Found a known certificate '{knownCertificate.Thumbprint}' with the same hash but failed to build its chain.", e); } return(false); } if (knownCertChain.ChainElements.Count != userChain.ChainElements.Count) { return(false); } for (var i = 0; i < knownCertChain.ChainElements.Count; i++) { // We walk the chain and compare the user certificate vs one of the existing certificate with same pinning hash var currentElementPinningHash = userChain.ChainElements[i].Certificate.GetPublicKeyPinningHash(); if (currentElementPinningHash != knownCertChain.ChainElements[i].Certificate.GetPublicKeyPinningHash()) { issuerPinningHash = currentElementPinningHash; return(false); } } return(true); }
public SecurityModule(FhirServerConfiguration fhirServerConfiguration) { EnsureArg.IsNotNull(fhirServerConfiguration, nameof(fhirServerConfiguration)); _securityConfiguration = fhirServerConfiguration.Security; }
/// <summary> /// 默认的构造函数,实例化一个新的OPC UA类 /// </summary> public OpcUaClient( ) { dic_subscriptions = new Dictionary <string, Subscription>( ); var certificateValidator = new CertificateValidator( ); certificateValidator.CertificateValidation += (sender, eventArgs) => { if (ServiceResult.IsGood(eventArgs.Error)) { eventArgs.Accept = true; } else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted) { eventArgs.Accept = true; } else { throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo)); } }; SecurityConfiguration securityConfigurationcv = new SecurityConfiguration { AutoAcceptUntrustedCertificates = true, RejectSHA1SignedCertificates = false, MinimumCertificateKeySize = 1024, }; certificateValidator.Update(securityConfigurationcv); // Build the application configuration application = new ApplicationInstance { ApplicationType = ApplicationType.Client, ConfigSectionName = OpcUaName, ApplicationConfiguration = new ApplicationConfiguration { ApplicationName = OpcUaName, ApplicationType = ApplicationType.Client, CertificateValidator = certificateValidator, ServerConfiguration = new ServerConfiguration { MaxSubscriptionCount = 100000, MaxMessageQueueSize = 1000000, MaxNotificationQueueSize = 1000000, MaxPublishRequestCount = 10000000, }, SecurityConfiguration = new SecurityConfiguration { AutoAcceptUntrustedCertificates = true, RejectSHA1SignedCertificates = false, MinimumCertificateKeySize = 1024, }, TransportQuotas = new TransportQuotas { OperationTimeout = 6000000, MaxStringLength = int.MaxValue, MaxByteStringLength = int.MaxValue, MaxArrayLength = 65535, MaxMessageSize = 419430400, MaxBufferSize = 65535, ChannelLifetime = -1, SecurityTokenLifetime = -1 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = -1, MinSubscriptionLifetime = -1, }, DisableHiResClock = true } }; // Assign a application certificate (when specified) // if (ApplicationCertificate != null) // application.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate = new CertificateIdentifier(_options.ApplicationCertificate); m_configuration = application.ApplicationConfiguration; }
public EmbeddedHtmlResult(PathString pathBase, string file, SecurityConfiguration securityConfiguration) { path = pathBase.Value; this.file = file; this.securityConfiguration = securityConfiguration; }
private const int KeySize = 512; // sector size public SecretProtection(SecurityConfiguration config) { _config = config; _serverMasterKey = new Lazy <byte[]>(LoadMasterKey); }
public void Should_return_the_current_configuration() { const string expectedOutput = @"Ignore missing configuration: True ------------------------------------------------------------------------------------ FluentSecurity.Specification.TestData.BlogController > DeletePost FluentSecurity.Policy.RequireAnyRolePolicy (Owner or Publisher) FluentSecurity.Specification.TestData.BlogController > Index FluentSecurity.Policy.DenyAnonymousAccessPolicy ------------------------------------------------------------------------------------"; var securityConfiguration = new SecurityConfiguration(configuration => { configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse); configuration.Advanced.IgnoreMissingConfiguration(); configuration.For<BlogController>(x => x.DeletePost(0)).DenyAnonymousAccess().RequireAnyRole(UserRole.Owner, UserRole.Publisher); configuration.For<BlogController>(x => x.Index()).DenyAnonymousAccess(); }); SecurityConfigurator.SetConfiguration(securityConfiguration); // Act var whatIHave = securityConfiguration.WhatDoIHave(); // Assert Assert.That(whatIHave, Is.EqualTo(expectedOutput)); }