Exemplo n.º 1
0
        static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json");

#if DEBUG
            // configurationBuilder = configurationBuilder.AddUserSecrets<Program>();
#endif
            var configuration          = configurationBuilder.Build();
            var converterConfiguration = ConfigurationBinder.Get <ConverterConfiguration>(configuration.GetSection("FilesData"));


            Console.WriteLine("Convertion started.....");
            //CustomerBuilder cb = new CustomerBuilder();
            //cb.BuildCustomers();

            //ProductsBuilder pb = new ProductsBuilder();
            //pb.BuildProducts();

            IWorker worker = new Worker(converterConfiguration);
            worker.CreateDB();

            Console.WriteLine("Convertion finished");
            Console.ReadKey();
        }
 /// <summary>
 /// Adds LiteX SQLite Cache manager services
 /// </summary>
 /// <param name="services"></param>
 /// <param name="config">SQLite configuration settings, default: use 'SQLiteConfig' from appsettings.json</param>
 /// <returns></returns>
 public static IServiceCollection AddLiteXSQLiteCache(this IServiceCollection services, SQLiteConfig config = null)
 {
     //IL_0019: Unknown result type (might be due to invalid IL or missing references)
     //IL_001e: Expected O, but got Unknown
     //IL_002b: Unknown result type (might be due to invalid IL or missing references)
     //IL_0030: Unknown result type (might be due to invalid IL or missing references)
     if (config == null)
     {
         IConfiguration        requiredService = ServiceProviderServiceExtensions.GetRequiredService <IConfiguration>((IServiceProvider)ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services));
         IConfigurationSection section         = requiredService.GetSection(SQLiteCacheDefaults.SettingsSection);
         config = ((section != null) ? ConfigurationBinder.Get <SQLiteConfig>(section) : null);
         if (config == null)
         {
             config = new SQLiteConfig
             {
                 FileName      = SQLiteCacheDefaults.FileName,
                 FilePath      = SQLiteCacheDefaults.FilePath,
                 OpenMode      = 0,
                 CacheMode     = 0,
                 EnableLogging = LiteXCacheDefaults.EnableLogging
             };
         }
         config.FilePath = ((!string.IsNullOrWhiteSpace(config.FilePath)) ? config.FilePath : SQLiteCacheDefaults.FilePath);
     }
     return(services.AddLiteXSQLiteCache(delegate(SQLiteConfig option)
     {
         //IL_0029: Unknown result type (might be due to invalid IL or missing references)
         //IL_003a: Unknown result type (might be due to invalid IL or missing references)
         option.FileName = config.FileName;
         option.FilePath = config.FilePath;
         option.OpenMode = config.OpenMode;
         option.CacheMode = config.CacheMode;
     }));
 }
        public static void UseDbConnection(this IApplicationBuilder app, IConfiguration configuration)
        {
            var dbConnections = ConfigurationBinder.Get <List <DbConnection> >(configuration.GetSection(typeof(DbConnection).Name));

            OrmLiteConfig.DialectProvider = MySqlDialect.Instance;

            foreach (var item in dbConnections)
            {
                if (string.IsNullOrWhiteSpace(item.ConnectionString) || string.IsNullOrWhiteSpace(item.ConnectionName))
                {
                    var msg = "ConnectionString Or ConnectionName Can Not Be NULL";
                    Console.WriteLine(msg);
                    throw new ArgumentNullException(msg);
                }

                IOrmLiteDialectProvider provider;
                if (item.DbType == DatabaseType.MySql)
                {
                    provider = MySqlDialect.Instance;
                }
                else
                {
                    provider = SqlServerDialect.Instance;
                }

                if (OrmLiteConnectionFactory.NamedConnections.ContainsKey(item.ConnectionName))
                {
                    var msg = $"ConnectionName is {item.ConnectionName} Is Already Register";
                    Console.WriteLine(msg);
                    throw new ArgumentException(msg);
                }

                DbFactory.Instance.RegisterConnection(item.ConnectionName, item.ConnectionString, provider);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Main entry point for application.
        /// </summary>
        /// <param name="configFile">Filepath to configuration file.</param>
        public void Main(string configFile)
        {
            if (configFile == null || string.IsNullOrWhiteSpace(configFile))
            {
                throw new ArgumentNullException(nameof(configFile));
            }

            var configPath = Path.Combine(Directory.GetCurrentDirectory(), configFile);

            if (!File.Exists(configPath))
            {
                throw new ArgumentException($"{configFile} not found", nameof(configFile));
            }

            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile(configPath, false);

            var config = configBuilder.Build();
            ReportConfiguration appConfiguration = ConfigurationBinder.Get <ReportConfiguration>(config);
            var selectedReports = ParseReports(appConfiguration.Reports ?? Array.Empty <string>());

            if (selectedReports.Any())
            {
                this.Run(selectedReports, appConfiguration.AzureDevOps).Wait();
            }
            else
            {
                WriteHelptext();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Get the credentials from the command line
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static Options GetOptionsFromConfiguration(string[] args)
        {
            Dictionary <string, string> mapping = new Dictionary <string, string>
            {
                { "--tenant-id", "SharedTokenCacheTenantId" },
                { "--app-owner", "SharedTokenCacheUsername" },
                { "--client-id", "ClientId" },
                { "--spa-redirect-uri", "SpaRedirectUri" },
                { "--web-redirect-uri", "WebRedirectUri" },
                { "--app-name", "AppName" },
            };
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddCommandLine(args, mapping);
            IConfiguration configuration = configurationBuilder.Build();
            DefaultAzureCredentialOptions defaultAzureCredentialOptions = ConfigurationBinder.Get <DefaultAzureCredentialOptions>(configuration);

            defaultAzureCredentialOptions.ExcludeManagedIdentityCredential    = true;
            defaultAzureCredentialOptions.ExcludeInteractiveBrowserCredential = false;
            defaultAzureCredentialOptions.InteractiveBrowserTenantId          = defaultAzureCredentialOptions.SharedTokenCacheTenantId;

            Options options = new Options();

            options.Action         = args.FirstOrDefault(a => !a.StartsWith("--"));
            options.SpaRedirectUri = ConfigurationBinder.GetValue <string>(configuration, "SpaRedirectUri", null);
            options.WebRedirectUri = ConfigurationBinder.GetValue <string>(configuration, "WebRedirectUri", null);
            options.AppName        = ConfigurationBinder.GetValue <string>(configuration, "AppName", null);
            options.ClientId       = ConfigurationBinder.GetValue <string>(configuration, "ClientId", null);
            options.DefaultAzureCredentialOptions = defaultAzureCredentialOptions;
            return(options);
        }
Exemplo n.º 6
0
 /// <summary>
 /// 配置服务
 /// </summary>
 /// <param name="services"></param>
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddApplication <AppHostModule>(options =>
     {
         var assemblyPlugins = ConfigurationBinder.Get <string[]>(Congiguration.GetSection("assemblyPlugins"));
         options.PlugInSources.Add(new AssemblyNamePlugInSource(assemblyPlugins.ToList()));
     });
 }
Exemplo n.º 7
0
        private static AppConfiguration GetRulesets()
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("validation-rules.json");

            IConfiguration config = builder.Build();

            var rulesets = ConfigurationBinder.Get <AppConfiguration>(config);

            return(rulesets);
        }
        public static AuthConfig ReadJsonFromFile(string path)
        {
            IConfiguration configuration;
            var            builder = new ConfigurationBuilder()
                                     .SetBasePath(Directory.GetCurrentDirectory())
                                     .AddJsonFile(path);

            configuration = builder.Build();
            return(ConfigurationBinder.Get <AuthConfig>(configuration));
        }
Exemplo n.º 9
0
        private IOptions <SecurityModelOptions> GetSecurityAccessProviderOptions()
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appSettings.json");
            var config       = configBuilder.Build();
            var optionsModel = ConfigurationBinder.Get <SecurityModelOptions>(config.GetSection("SecurityModelOptions"));
            var options      = Options.Create(optionsModel);

            return(options);
        }
Exemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var config = ConfigurationBinder.Get <Authentication>(Configuration.GetSection(typeof(Authentication).Name));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme    = "JwtBearer";
            }).AddJwtBearer("JwtBearer", options =>
            {
                options.Audience = config.JwtBearer.Audience;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.JwtBearer.SecurityKey)),

                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer    = config.JwtBearer.Issuer,

                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience    = config.JwtBearer.Audience,

                    // Validate the token expiry
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero
                };
            });

            services.AddTransient(typeof(IRepository <>), typeof(Repository <>));
            services.AddTransient(typeof(IRepository <,>), typeof(Repository <,>));

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info()
                {
                    Title = "MyApi", Version = "V1"
                });

                options.AddSecurityDefinition("MyApi", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
            });
        }
        public void OnGet()
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appSettings.json");
            var config       = configBuilder.Build();
            var optionsModel = ConfigurationBinder.Get <SecurityModelOptions>(config.GetSection("SecurityModelOptions"));
            var options      = Options.Create(optionsModel);
            var UserClaims   = HttpContext.User.Claims;
            var groups       = UserClaims.Where(x => x.Type == "groups").Select(v => v.Value);

            Roles = options.Value.SecurityRoles.Where(x => groups.Any(a => a == x.SecurityGroupId));
        }
Exemplo n.º 12
0
        public static ResillienceContainer EnableZeus(this ResillienceContainer container, string assemblyName, IConfiguration configuration)
        {
            ZeusOptions zeusOptions = ConfigurationBinder.Get <ZeusOptions>((IConfiguration)(object)configuration.GetSection("Resillience:Zeus"));

            //DbContextOptionsBuilder<ZeusContext> optionsBuilder = new DbContextOptionsBuilder<ZeusContext>();
            //optionsBuilder.UseMySql(zeusOptions.Connection, b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name));

            container.Builder.Register(c =>
            {
                var optionsBuilder = new DbContextOptionsBuilder <ZeusContext>();
                optionsBuilder.UseMySql(zeusOptions.Connection);
                //optionsBuilder.UseMySql(zeusOptions.Connection, b => b
                //	.MigrationsAssembly(assemblyName));
                return(optionsBuilder.Options);
            }).InstancePerLifetimeScope();
            container.Builder.RegisterType <ZeusContext>().AsSelf().InstancePerLifetimeScope();
            container.Builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope();
            container.Builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
            container.Builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).Where(t => t.Name.EndsWith("Queries")).AsSelf()
            .AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
            container.Builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsClosedTypesOf(typeof(IRequestHandler <,>));
            container.Builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsClosedTypesOf(typeof(INotificationHandler <>));
            container.Builder.RegisterType <InMemoryBus>().As <IMediatorHandler>().InstancePerLifetimeScope();
            container.Builder.RegisterType <Mediator>().As <IMediator>().InstancePerLifetimeScope();

            container.Builder.Register((Func <IComponentContext, ServiceFactory>) delegate(IComponentContext context)
            {
                IComponentContext c2 = context.Resolve <IComponentContext>();
                return((Type t) => c2.Resolve(t));
            });

            #region Mapping

            List <Profile> autoMapperProfiles = (Assembly.GetEntryAssembly() !.GetTypes()).Where(p => p.BaseType == typeof(Profile))
                                                .Select(p => (Profile)Activator.CreateInstance(p)).ToList();

            container.Builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                foreach (Profile item in autoMapperProfiles)
                {
                    cfg.AddProfile(item);
                }
            }));
            container.Builder.Register(ctx => ctx.Resolve <MapperConfiguration>().CreateMapper()).As <IMapper>().InstancePerLifetimeScope();

            #endregion

            return(container);
        }
Exemplo n.º 13
0
        public void LoadingSettingsIncludesGlobalListsAndRoles()
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appSettings.json");
            var config       = configBuilder.Build();
            var optionsModel = ConfigurationBinder.Get <SecurityModelOptions>(config.GetSection("SecurityModelOptions"));
            var options      = Options.Create(optionsModel);

            options.Should().NotBeNull();
            options.Value.GlobalAllowActions.Count.Should().BeGreaterThan(0);
            options.Value.GlobalDenyActions.Count.Should().BeGreaterThan(0);
            options.Value.SecurityRoles.Count.Should().BeGreaterThan(0);
            options.Value.SecurityRoles[0].AllowActions.Count.Should().BeGreaterThan(0);
        }
Exemplo n.º 14
0
        private string CreateAccessToken(IEnumerable <Claim> claims, TimeSpan?expiration = null)
        {
            var config = ConfigurationBinder.Get <Authentication>(_configuration.GetSection(typeof(Authentication).Name));
            var now    = DateTime.UtcNow;

            var jwtSecurityToken = new JwtSecurityToken(
                issuer: config.JwtBearer.Issuer,
                audience: config.JwtBearer.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(expiration ?? TimeSpan.FromSeconds(config.JwtBearer.Expiration)),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.JwtBearer.SecurityKey)), SecurityAlgorithms.HmacSha256)
                );

            return(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken));
        }
Exemplo n.º 15
0
        protected override void Load(ContainerBuilder builder)
        {
            ZeusOptions zeusOptions = ConfigurationBinder.Get <ZeusOptions>((IConfiguration)(object)Configuration.GetSection("Zeus"));

            #region AutoMapper
            List <Profile> autoMapperProfiles = (Assembly.GetEntryAssembly() !.GetTypes()).Where(p => p.BaseType == typeof(Profile)).Select(p => (Profile)Activator.CreateInstance(p)).ToList();

            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                foreach (Profile item in autoMapperProfiles)
                {
                    cfg.AddProfile(item);
                }
            }));
            builder.Register(ctx => ctx.Resolve <MapperConfiguration>().CreateMapper()).As <IMapper>().InstancePerLifetimeScope();
            #endregion

            #region IHttpClientFactory
            //builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().InstancePerLifetimeScope();
            //builder.RegisterType<HttpClientFactory>().As<IHttpClientFactory>().InstancePerLifetimeScope();
            #endregion

            #region Data
            builder.Register(c =>
            {
                var optionsBuilder = new DbContextOptionsBuilder <ZeusContext>();
                optionsBuilder.UseMySql(zeusOptions.Connection);
                return(optionsBuilder.Options);
            }).InstancePerLifetimeScope();

            builder.RegisterType <ZeusContext>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).Where(t => t.Name.EndsWith("Queries")).AsSelf()
            .AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsClosedTypesOf(typeof(IRequestHandler <,>));
            builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsClosedTypesOf(typeof(INotificationHandler <>));
            builder.RegisterType <InMemoryBus>().As <IMediatorHandler>().InstancePerLifetimeScope();
            builder.RegisterType <Mediator>().As <IMediator>().InstancePerLifetimeScope();

            builder.Register((Func <IComponentContext, ServiceFactory>) delegate(IComponentContext context)
            {
                IComponentContext c2 = context.Resolve <IComponentContext>();
                return((Type t) => c2.Resolve(t));
            });
            #endregion
        }
Exemplo n.º 16
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args).
        UseApplicationInsights().
        ConfigureAppConfiguration((hostingContext, config) =>
        {
            Configuration = config.Build();
        }).
        ConfigureServices(s =>
        {
            s.AddMvc();

            #region CosmosDB
            var cosmosDbConfig = ConfigurationBinder.Get <CosmosDbConfig>(Configuration.GetSection("CosmosDb"));
            s.AddSingleton(cosmosDbConfig);

            var connectionPolicy = new ConnectionPolicy
            {
                ConnectionMode            = ConnectionMode.Direct,
                ConnectionProtocol        = Protocol.Tcp,
                UseMultipleWriteLocations = true
            };
            if (cosmosDbConfig.PreferredLocations != null && cosmosDbConfig.PreferredLocations.Any() && cosmosDbConfig.PreferredLocations.All(l => AllowedLocations.Contains(l)))
            {
                // write
                connectionPolicy.SetCurrentLocation(cosmosDbConfig.PreferredLocations.First());

                // read
                foreach (var location in cosmosDbConfig.PreferredLocations)
                {
                    connectionPolicy.PreferredLocations.Add(location);
                }
            }

            var client = new DocumentClient(new Uri(cosmosDbConfig.Endpoint), cosmosDbConfig.Key, connectionPolicy);
            client.OpenAsync().GetAwaiter().GetResult();

            s.AddSingleton(client);
            #endregion
        }).
        Configure(app =>
        {
            app.UseHttpsRedirection();
            app.UseMvc();
        });
Exemplo n.º 17
0
        public static IServiceCollection AddSocketClient(this IServiceCollection services, IConfiguration config)
        {
            services.Configure <RemoteOptions>(config);
            services.AddSingleton <ClientWaits>();
            services.AddSingleton <ClientMessageRouter, DefaultClientMessageRouter>();
            services.AddSingleton <IPacketCodec, DefaultPacketCodec>();
            services.AddSingleton <IMessageHandlerProvider, DotNettyMessageHandlerProvider>();
            services.AddSingleton <ISocketClientProvider, DottNettyClientAdapter>();
            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.AddSingleton <ISocketClientPoolContainer, SocketClientPoolContainer>();

            var options = ConfigurationBinder.Get <RemoteOptions>(config);

            if (!string.IsNullOrEmpty(options.CommandAssembly))
            {
                services.AddCommands(new List <string>()
                {
                    options.CommandAssembly
                });
            }

            return(services);
        }
Exemplo n.º 18
0
 public static IHostBuilder UseArgo(this IHostBuilder builder, IConfiguration config)
 {
     return(builder.ConfigureServices((services) =>
     {
         services.Configure <ServerOptions>(config);
         services.AddSingleton <IPassThroughRuleProvider, PassThroughRuleProvider>();
         services.AddSingleton <IMessageRouter, MessageRouter>();
         services.AddSingleton <IPacketCodec, DefaultPacketCodec>();
         services.AddSingleton <INetListenerProvider, DotNettyListenerProvider>();
         var appSessionContainer = new AppSessionContainer <AppSession>();
         services.AddSingleton(appSessionContainer);
         services.AddSingleton <IHostedService, NetListenerService>();
         services.AddSingleton <IServerMonitor, DefaultServerMonitor>();
         services.AddSingleton <IHostedService, MonitorService>();
         var options = ConfigurationBinder.Get <ServerOptions>(config);
         if (options != null && options.Listeners.Any())
         {
             options.Listeners.ForEach(op =>
             {
                 services.AddCommands(op.CommandAssemblies);
             });
         }
     }));
 }
Exemplo n.º 19
0
        public static IHostBuilder Create(IConfiguration configuration, bool runAsWindowsService, ILogger logger)
        {
            var builder = new HostBuilder();

            var serverOptions = new OakproxyServerOptions();

            serverOptions.Configure(configuration.GetSection("Server"));

            var proxyOptions = ConfigurationBinder.Get <ProxyOptions>(configuration);

            if (!OptionsAreValid(serverOptions, logger, "Server") || !OptionsAreValid(proxyOptions, logger))
            {
                return(null);
            }

            var subsystemConfiguration = ConfigurationBinder.Get <HostingSubsystemConfiguration>(configuration.GetSection("Configuration"),
                                                                                                 binderOptions => binderOptions.BindNonPublicProperties = true) ?? HostingSubsystemConfiguration.Empty();

            builder
            .UseContentRoot(Program.GetExecutableDirectory())
            .ConfigureHostConfiguration(builder => builder.AddConfiguration(subsystemConfiguration.Host));

            if (runAsWindowsService)
            {
                builder.UseWindowsService();
            }

            builder
            .ConfigureAppConfiguration(builder => builder.AddConfiguration(configuration))
            .ConfigureLogging((hostBuilderContext, loggingBuilder) =>
            {
                if (subsystemConfiguration.Logging.Exists())
                {
                    loggingBuilder.AddConfiguration(subsystemConfiguration.Logging);
                }
                else
                {
                    loggingBuilder.AddFilter(null, serverOptions.LogLevelInternal);
                }

                if (runAsWindowsService)
                {
                    loggingBuilder.AddProvider(new DeferringLoggerProvider(new EventLogLoggerProvider(new EventLogSettings
                    {
                        SourceName = "OAKProxy"
                    })));
                }
                else
                {
                    loggingBuilder.AddConsole();
                }
            })
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .ConfigureServices((context, services) =>
            {
                services.AddOptions <ProxyOptions>()
                .Bind(configuration)
                .ValidateDataAnnotations();

                services.AddSingleton(Options.Create(serverOptions));

                if (!String.IsNullOrWhiteSpace(serverOptions.ApplicationInsightsKey))
                {
                    services.AddApplicationInsightsTelemetry(options =>
                    {
                        options.InstrumentationKey = serverOptions.ApplicationInsightsKey;
                        subsystemConfiguration.ApplicationInsights.Bind(options);
                    });
                    services.AddApplicationInsightsTelemetryProcessor <OakproxyTelemetryProcessor>();
                }

                services.AddTransient <IStartupFilter, HostingPipelineStartup>();

                if (serverOptions.UseForwardedHeaders || serverOptions.UseAzureApplicationGateway)
                {
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.All;
                        options.KnownNetworks.Clear();
                        options.KnownProxies.Clear();
                        subsystemConfiguration.ForwardedHeaders.Bind(options);

                        if (serverOptions.UseAzureApplicationGateway)
                        {
                            options.ForwardedHostHeaderName = "X-Original-Host";
                        }
                    });
                }

                if (serverOptions.KeyManagement != null)
                {
                    var dataProtectionBuilder = services.AddDataProtection();
                    var kmOptions             = serverOptions.KeyManagement;

                    kmOptions.LoadCertificates(configuration.GetSection(ConfigurationPath.Combine("Server", "KeyManagement")));

                    if (!String.IsNullOrEmpty(kmOptions.StoreToFilePath))
                    {
                        var directoryInfo = new DirectoryInfo(kmOptions.StoreToFilePath);
                        if (!directoryInfo.Exists)
                        {
                            throw new DirectoryNotFoundException("The specified key storage directory does not exist.");
                        }
                        dataProtectionBuilder.PersistKeysToFileSystem(directoryInfo);
                    }
                    else if (!String.IsNullOrEmpty(kmOptions.StoreToBlobContainer))
                    {
                        var blobUri = new Uri(kmOptions.StoreToBlobContainer);
                        if (String.IsNullOrEmpty(blobUri.Query))
                        {
                            var azureServiceTokenProvider = new AzureServiceTokenProvider();
                            var tokenAndFrequency         = StorageTokenRenewerAsync(azureServiceTokenProvider, CancellationToken.None)
                                                            .GetAwaiter().GetResult();

                            TokenCredential tokenCredential = new TokenCredential(tokenAndFrequency.Token,
                                                                                  StorageTokenRenewerAsync,
                                                                                  azureServiceTokenProvider,
                                                                                  tokenAndFrequency.Frequency.Value);

                            var storageCredentials = new StorageCredentials(tokenCredential);
                            var cloudBlockBlob     = new CloudBlockBlob(blobUri, storageCredentials);
                            dataProtectionBuilder.PersistKeysToAzureBlobStorage(cloudBlockBlob);
                        }
                        else
                        {
                            dataProtectionBuilder.PersistKeysToAzureBlobStorage(blobUri);
                        }
                    }

                    if (!String.IsNullOrEmpty(kmOptions.ProtectWithKeyVaultKey))
                    {
                        var keyVaultSection = configuration.GetSection(ConfigurationPath.Combine("Server", "KeyVault"));
                        var kvOptions       = new KeyVaultOptions(keyVaultSection);

                        var keyIdBuilder = new UriBuilder(kvOptions.VaultUri)
                        {
                            Path = $"/keys/${kmOptions.ProtectWithKeyVaultKey}"
                        };
                        var keyId = keyIdBuilder.Uri.ToString();

                        if (kvOptions.ClientId == null)
                        {
                            // Use Managed Identity
                            var azureServiceTokenProvider = new AzureServiceTokenProvider();
                            var authenticationCallback    = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback);
                            dataProtectionBuilder.ProtectKeysWithAzureKeyVault(new KeyVaultClient(authenticationCallback), keyId);
                        }
                        else
                        {
                            if (kvOptions.ClientSecret != null)
                            {
                                dataProtectionBuilder.ProtectKeysWithAzureKeyVault(keyId, kvOptions.ClientId, kvOptions.ClientSecret);
                            }
                            else if (kvOptions.Certificate != null)
                            {
                                dataProtectionBuilder.ProtectKeysWithAzureKeyVault(keyId, kvOptions.ClientId, kvOptions.Certificate);
                            }
                        }
                    }
                    else if (kmOptions.ProtectWithCertificate != null)
                    {
                        dataProtectionBuilder.ProtectKeysWithCertificate(kmOptions.ProtectWithCertificate);

                        if (kmOptions.UnprotectWithCertificates != null)
                        {
                            dataProtectionBuilder.UnprotectKeysWithAnyCertificate(kmOptions.UnprotectWithCertificates);
                        }
                    }
                    else if (kmOptions.ProtectWithDpapiNg != null)
                    {
                        if (kmOptions.ProtectWithDpapiNg.UseSelfRule)
                        {
                            dataProtectionBuilder.ProtectKeysWithDpapiNG();
                        }
                        else
                        {
                            dataProtectionBuilder.ProtectKeysWithDpapiNG(kmOptions.ProtectWithDpapiNg.DescriptorRule, kmOptions.ProtectWithDpapiNg.DescriptorFlags);
                        }
                    }
                    else
                    {
                        throw new Exception("Unvalidated options would have allowed for unprotected key storage.");
                    }
                }

                services.AddHttpContextAccessor();
                services.AddHealthChecks();
                services.AddOakproxy(proxyOptions);
            })
            .ConfigureWebHost(configure =>
            {
                configure.UseUrls(serverOptions.Urls);
                configure.UseKestrel((builderContext, options) =>
                {
                    options.Configure(subsystemConfiguration.Kestrel);

                    if (serverOptions.HttpsCertificate != null)
                    {
                        options.ConfigureHttpsDefaults(configureHttps => configureHttps.ServerCertificate = serverOptions.HttpsCertificate);
                    }
                });
                configure.Configure(builder => builder.UseOakproxy());
            });

            return(builder);
        }
Exemplo n.º 20
0
 public Startup(IConfiguration configuration)
 {
     Configuration = configuration;
     SFDCConfig    = ConfigurationBinder.Get <SalesforceConfig>(Configuration.GetSection(Keys.Sections.SalesforceSettings));
     BlendConfig   = ConfigurationBinder.Get <BlendConfig>(Configuration.GetSection(Keys.Sections.BlendSettings));
 }
Exemplo n.º 21
0
        /// <summary>
        /// 获取Json配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileDir">文件目录(格式:D:\JsonConfigs)</param>
        /// <param name="fileName">文件名称(格式:xxx.json)</param>
        /// <returns></returns>
        public static T GetValue <T>(string fileDir, string fileName)
        {
            IConfiguration configuration = GetJsonConfiguration(fileDir, fileName);

            return(ConfigurationBinder.Get <T>(configuration));
        }
Exemplo n.º 22
0
 public static T Get <T>(this IConfiguration configuration)
 {
     return(ConfigurationBinder.Get <T>(configuration));
 }
Exemplo n.º 23
0
 public static T GetSection <T>(this IConfiguration configuration, string key)
 {
     return(ConfigurationBinder.Get <T>(configuration.GetSection(key)));
 }