internal async Task UpdateSettingsAsync(CorsSettings corsSettings) { var siteSettings = await _siteService.LoadSiteSettingsAsync(); siteSettings.Properties[nameof(CorsSettings)] = JObject.FromObject(corsSettings); await _siteService.UpdateSiteSettingsAsync(siteSettings); }
private void BindCorsSettings() { var corsSettings = new CorsSettings(); configuration.GetSection(nameof(CorsSettings)).Bind(corsSettings); SettingsProvider.CorsSettings = corsSettings; }
public ContainerOptions() { Database = new DatabaseSettings(); Token = new TokenSettings(); Caching = new CachingSettings(); CORS = new CorsSettings(); }
public static CorsOrigins.EnvironmentType GetCorsEnvironmentName(this IConfiguration configuration) { CorsSettings settings = configuration.GetSection(typeof(CorsSettings).Name).Get <CorsSettings>(); CorsOrigins.EnvironmentType environment = (CorsOrigins.EnvironmentType)Enum.Parse(typeof(CorsOrigins.EnvironmentType), settings?.Environment, true); return(environment); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var tokenSettings = new TokenSettings(); Configuration.GetSection(nameof(TokenSettings)).Bind(tokenSettings); var corsSettings = new CorsSettings(); Configuration.GetSection(nameof(CorsSettings)).Bind(corsSettings); services.AddDbContextPool <DroneContext>(options => options .UseMySql(Configuration .GetConnectionString("DatabaseConnection"), mySqlOptions => mySqlOptions .ServerVersion(new ServerVersion(new Version(8, 0, 18), ServerType.MySql)) )); services.AddCors(option => { option.AddPolicy("CorsPolicy", builder => { builder .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .WithOrigins(corsSettings.AllowedOrigin); }); }); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.Secret)), ValidIssuer = tokenSettings.Issuer, ValidAudience = tokenSettings.Audience, ValidateIssuer = false, ValidateAudience = false }; }); services.AddSingleton(tokenSettings); services.AddSingleton(corsSettings); services.AddSignalR(); services.AddScoped <IContainerRepository, ContainerRepository>(); services.AddControllers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var config = new ApplicationSettings(); Configuration.Bind("ApplicationSettings", config); services.AddControllers(); BootStrapper.RegisterServices(services, Configuration); CorsSettings.RegisterCors(services); SwaggerSettings.RegisterSwagger(services); }
public static void UseDefaultCorsPolicy(this IApplicationBuilder app, CorsSettings settings) { if (settings.AllowedOrigins == null) { throw new ArgumentNullException(nameof(settings.AllowedOrigins)); } app.UseCors(builder => builder.WithOrigins(settings.AllowedOrigins.ToArray()) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }
public void AddProvider(IServiceCollection services, ISettings <string, object> settings) { CorsSettings corsSettings = settings.GetSetting <CorsSettings>(); services.AddCors(options => { options.AddPolicy(corsSettings.Policy, builder => builder .WithOrigins(corsSettings.WithOrigins) .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); }
public static void AddConfiuredCors(this IServiceCollection services, IConfiguration configuration) { var corsSettings = new CorsSettings(); configuration.GetSection(nameof(CorsSettings)).Bind(corsSettings); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder .WithOrigins(corsSettings.AllowedHosts) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); }
internal static void AddCrossOriginPolicy(this IServiceCollection services) { CorsSettings corsSettings = default(CorsSettings); var sp = services.BuildServiceProvider(); corsSettings = (CorsSettings)sp.GetService(typeof(CorsSettings)); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .WithOrigins(corsSettings.AllowedOrgins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <CorsSettings> corsSettings) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Use JWT Bearer Authentication app.UseAuthentication(); // Use Swaggger UI app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Webshop REST API"); options.DocExpansion(DocExpansion.List); }); CorsSettings cors = corsSettings.Value; // Use Cross-Origin-Resource-Sharing app.UseCors(builder => { builder .WithOrigins(cors.AllowedOrigins) .WithMethods(cors.AllowedMethods) .WithHeaders(cors.AllowedHeaders); }); // Use Routing app.UseRouting(); // Use Authorization app.UseAuthorization(); // Map Controller + SignalR Endpoints app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <WebshopHub>("/webshop"); }); }
internal static void AddChainOfOptions(this IServiceCollection services, IConfiguration configuration) { //API settings services.Configure <ApiSettings>(configuration.GetSection("ApiSettings")); //SendGrid Settings services.Configure <SendGridSettings>(configuration.GetSection("SendGridSettings")); //BasicEmail Settings services.Configure <BasicEmailSettings>(configuration.GetSection("BasicEmailSettings")); services.AddTransient <Mail>(); services.AddTransient <MailHelper>(); //Cors settings var corsSettings = new CorsSettings(); configuration.Bind("CorsPolicy", corsSettings); services.AddSingleton <CorsSettings>(corsSettings); }
public async Task <ActionResult> IndexPOST() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageCorsSettings)) { return(Unauthorized()); } var model = new CorsSettingsViewModel(); var configJson = Request.Form["CorsSettings"].First(); model.Policies = JsonConvert.DeserializeObject <CorsPolicyViewModel[]>(configJson); var corsPolicies = new List <CorsPolicySetting>(); foreach (var settingViewModel in model.Policies) { corsPolicies.Add(new CorsPolicySetting { Name = settingViewModel.Name, AllowAnyHeader = settingViewModel.AllowAnyHeader, AllowAnyMethod = settingViewModel.AllowAnyMethod, AllowAnyOrigin = settingViewModel.AllowAnyOrigin, AllowCredentials = settingViewModel.AllowCredentials, AllowedHeaders = settingViewModel.AllowedHeaders, AllowedMethods = settingViewModel.AllowedMethods, AllowedOrigins = settingViewModel.AllowedOrigins, IsDefaultPolicy = settingViewModel.IsDefaultPolicy }); } var corsSettings = new CorsSettings() { Policies = corsPolicies }; await _corsService.UpdateSettingsAsync(corsSettings); await _notifier.SuccessAsync(TH["The CORS settings have updated successfully."]); return(View(model)); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var corsSettings = CorsSettings.GetCorsSettings()[0]; var cors = new EnableCorsAttribute( origins: corsSettings.Origins, headers: corsSettings.Headers, methods: corsSettings.Methods, exposedHeaders: corsSettings.ExposedHeaders); config.EnableCors(cors); }
private void ConfigureSettings(IServiceCollection services) { var corsSettings = new CorsSettings(); new ConfigureFromConfigurationOptions <CorsSettings>(Configuration.GetSection("CorsSettings")).Configure(corsSettings); services.AddSingleton(corsSettings); var mongoConnection = new MongoConnection(); new ConfigureFromConfigurationOptions <MongoConnection>(Configuration.GetSection("MongoConnection")).Configure(mongoConnection); services.AddSingleton(mongoConnection); var redisConnection = new RedisConnection(); new ConfigureFromConfigurationOptions <RedisConnection>(Configuration.GetSection("RedisConnection")).Configure(redisConnection); services.AddSingleton(redisConnection); var googleSettings = new GoogleSettings(); new ConfigureFromConfigurationOptions <GoogleSettings>(Configuration.GetSection("GoogleSettings")).Configure(googleSettings); services.AddSingleton(googleSettings); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); using (StreamReader file = File.OpenText(@"./Data/EnabledCors.json")) { string content = file.ReadToEnd(); } CorsSettings corsSettings = JsonConvert.DeserializeObject <CorsSettings>(File.ReadAllText(@"./Data/EnabledCors.json")); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins(corsSettings.Hosts.ToArray()) .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
private string[] GetAllowedOrigins() { CorsSettings corsSettings = Configuration.GetSection(nameof(CorsSettings)).Get <CorsSettings>(); return(corsSettings.AllowedOrigins?.Split(";").ToArray()); }
public AthenaServicesConfiguration(IConfiguration configuration) { _configuration = configuration; _corsSettings = new CorsSettings(configuration); }
public static IApplicationBuilder UseCorsCommon(this IApplicationBuilder app, CorsSettings corsSettings) { if (!string.IsNullOrEmpty(corsSettings.AllowOrigin)) { app.UseCors(m => { if (corsSettings.AllowOrigin == "*") { m.AllowAnyOrigin(); } else { m.WithHeaders(corsSettings.AllowOrigin.Split(",", StringSplitOptions.RemoveEmptyEntries)); } if (corsSettings.AllowMethod == "*") { m.AllowAnyMethod(); } else { m.WithHeaders(corsSettings.AllowMethod.Split(",", StringSplitOptions.RemoveEmptyEntries)); } if (corsSettings.AllowHeader == "*") { m.AllowAnyHeader(); } else { m.WithHeaders(corsSettings.AllowHeader.Split(",", StringSplitOptions.RemoveEmptyEntries)); } }); } return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IDBInitializer dbInitializer, IAntiforgery antiforgery ) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseMiddleware <LoggingExceptionHandler>(); //The default HSTS value is 30 days.You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } var swaggerOptions = new WebApp.Utility.SwaggerOptions(); Configuration.GetSection(nameof(WebApp.Utility.SwaggerOptions)).Bind(swaggerOptions); app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", swaggerOptions.Description); }); //create DB on startup EnsureDbCreated(); dbInitializer.Initialize(); SettingsHandler.Settings.ReadSettings(); //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); var corsSettings = new CorsSettings(); Configuration.GetSection(nameof(CorsSettings)).Bind(corsSettings); app.UseCors(builder => { builder .WithOrigins(corsSettings.AllowedOrigins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); app.UseAuthentication(); app.UseSignalR(routes => { routes.MapHub <QueueHub>("/queueHub"); }); app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area=Patient}/{controller=Home}/{action=Index}/{id?}"); }); }
public OptionsRequestsMiddleware(RequestDelegate next, CorsSettings settings) { _next = next; _settings = settings; }
public static void ConfigureCors(this IServiceCollection services, string policyName, CorsSettings settings) { services.AddCors(options => { options.AddPolicy(policyName, builder => { builder.WithHeaders(settings.AllowedHeaders.Split(',')); builder.WithMethods(settings.AllowedMethods.Split(',')); builder.WithOrigins(settings.AllowedOrigins.Split(',')); }); }); }
public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IDalSettings, DalSettings>(); services.AddSingleton <IBookingSettings, BookingSettings>(); services.AddTransient <IUserInfo, UserInfo>(); services.AddSingleton <IAccountUpdatingSettings, AccountUpdatingSettings>(); services.AddSingleton <IProfileCachingSettings, ProfileCachingSettings>(); FrontendFilesSettings frontendFilesSettings = new FrontendFilesSettings(Configuration); services.AddSingleton <IFrontendFilesSettings>(frontendFilesSettings); FilesUploadingSettings filesUploadingSettings = new FilesUploadingSettings(Configuration); services.AddSingleton <IFilesUploadingSettings, FilesUploadingSettings>(); services.AddSingleton <IPaginationSettings, PaginationSettings>(); CorsSettings corsSettings = new CorsSettings(Configuration); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins(corsSettings.AllowedOrigins) .AllowAnyHeader() .AllowAnyMethod(); }); }); MapperConfiguration mappingConfig = new MapperConfiguration(config => { WebAPIMapping.Initialize(config); BlMapping.Initialize(config); DalMapping.Initialize(config); }); mappingConfig.CompileMappings(); services.AddSingleton <IMapper>(mappingConfig.CreateMapper()); services.AddControllers(); DalModule.Register(services); BlModule.Register(services); WebAPIModule.Register(services); Serilog.ILogger logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .CreateLogger(); services.AddLogging((builder) => { builder.AddSerilog(logger, dispose: true); }); JwtSettings jwtSettings = new JwtSettings(Configuration); services.AddSingleton <IJwtSettings>(jwtSettings); byte[] key = Encoding.UTF8.GetBytes(jwtSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = false; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, ValidIssuer = jwtSettings.Issuer, ValidateAudience = true, ValidAudiences = corsSettings.AllowedOrigins }; }); services.AddHttpContextAccessor(); services.Configure <FormOptions>(options => { // converting to bytes options.MultipartBodyLengthLimit = filesUploadingSettings.MaxMbSize * 1024 * 1024; }); services.AddMemoryCache(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = Path.Combine(frontendFilesSettings.StoragePath); }); }
public void AddAplication(IApplicationBuilder app, IWebHostEnvironment env, ISettings <string, object> settings) { CorsSettings corsSettings = settings.GetSetting <CorsSettings>(); app.UseCors(corsSettings.Policy); }
internal SiteConfigAutoGeneratedData(ResourceIdentifier id, string name, ResourceType type, string kind, int?numberOfWorkers, IList <string> defaultDocuments, string netFrameworkVersion, string phpVersion, string pythonVersion, string nodeVersion, string powerShellVersion, string linuxFxVersion, string windowsFxVersion, bool?requestTracingEnabled, DateTimeOffset?requestTracingExpirationTime, bool?remoteDebuggingEnabled, string remoteDebuggingVersion, bool?httpLoggingEnabled, bool?acrUseManagedIdentityCreds, string acrUserManagedIdentityID, int?logsDirectorySizeLimit, bool?detailedErrorLoggingEnabled, string publishingUsername, IList <NameValuePair> appSettings, IList <ConnStringInfo> connectionStrings, SiteMachineKey machineKey, IList <HandlerMapping> handlerMappings, string documentRoot, ScmType?scmType, bool?use32BitWorkerProcess, bool?webSocketsEnabled, bool?alwaysOn, string javaVersion, string javaContainer, string javaContainerVersion, string appCommandLine, ManagedPipelineMode?managedPipelineMode, IList <VirtualApplication> virtualApplications, SiteLoadBalancing?loadBalancing, Experiments experiments, SiteLimits limits, bool?autoHealEnabled, AutoHealRules autoHealRules, string tracingOptions, string vnetName, bool?vnetRouteAllEnabled, int?vnetPrivatePortsCount, CorsSettings cors, PushSettings push, ApiDefinitionInfo apiDefinition, ApiManagementConfig apiManagementConfig, string autoSwapSlotName, bool?localMySqlEnabled, int?managedServiceIdentityId, int?xManagedServiceIdentityId, string keyVaultReferenceIdentity, IList <IpSecurityRestriction> ipSecurityRestrictions, IList <IpSecurityRestriction> scmIpSecurityRestrictions, bool?scmIpSecurityRestrictionsUseMain, bool?http20Enabled, FtpsState?ftpsState, int?preWarmedInstanceCount, int?functionAppScaleLimit, string healthCheckPath, bool?functionsRuntimeScaleMonitoringEnabled, string websiteTimeZone, int?minimumElasticInstanceCount, IDictionary <string, AzureStorageInfoValue> azureStorageAccounts, string publicNetworkAccess) : base(id, name, type, kind) { NumberOfWorkers = numberOfWorkers; DefaultDocuments = defaultDocuments; NetFrameworkVersion = netFrameworkVersion; PhpVersion = phpVersion; PythonVersion = pythonVersion; NodeVersion = nodeVersion; PowerShellVersion = powerShellVersion; LinuxFxVersion = linuxFxVersion; WindowsFxVersion = windowsFxVersion; RequestTracingEnabled = requestTracingEnabled; RequestTracingExpirationTime = requestTracingExpirationTime; RemoteDebuggingEnabled = remoteDebuggingEnabled; RemoteDebuggingVersion = remoteDebuggingVersion; HttpLoggingEnabled = httpLoggingEnabled; AcrUseManagedIdentityCreds = acrUseManagedIdentityCreds; AcrUserManagedIdentityID = acrUserManagedIdentityID; LogsDirectorySizeLimit = logsDirectorySizeLimit; DetailedErrorLoggingEnabled = detailedErrorLoggingEnabled; PublishingUsername = publishingUsername; AppSettings = appSettings; ConnectionStrings = connectionStrings; MachineKey = machineKey; HandlerMappings = handlerMappings; DocumentRoot = documentRoot; ScmType = scmType; Use32BitWorkerProcess = use32BitWorkerProcess; WebSocketsEnabled = webSocketsEnabled; AlwaysOn = alwaysOn; JavaVersion = javaVersion; JavaContainer = javaContainer; JavaContainerVersion = javaContainerVersion; AppCommandLine = appCommandLine; ManagedPipelineMode = managedPipelineMode; VirtualApplications = virtualApplications; LoadBalancing = loadBalancing; Experiments = experiments; Limits = limits; AutoHealEnabled = autoHealEnabled; AutoHealRules = autoHealRules; TracingOptions = tracingOptions; VnetName = vnetName; VnetRouteAllEnabled = vnetRouteAllEnabled; VnetPrivatePortsCount = vnetPrivatePortsCount; Cors = cors; Push = push; ApiDefinition = apiDefinition; ApiManagementConfig = apiManagementConfig; AutoSwapSlotName = autoSwapSlotName; LocalMySqlEnabled = localMySqlEnabled; ManagedServiceIdentityId = managedServiceIdentityId; XManagedServiceIdentityId = xManagedServiceIdentityId; KeyVaultReferenceIdentity = keyVaultReferenceIdentity; IpSecurityRestrictions = ipSecurityRestrictions; ScmIpSecurityRestrictions = scmIpSecurityRestrictions; ScmIpSecurityRestrictionsUseMain = scmIpSecurityRestrictionsUseMain; Http20Enabled = http20Enabled; FtpsState = ftpsState; PreWarmedInstanceCount = preWarmedInstanceCount; FunctionAppScaleLimit = functionAppScaleLimit; HealthCheckPath = healthCheckPath; FunctionsRuntimeScaleMonitoringEnabled = functionsRuntimeScaleMonitoringEnabled; WebsiteTimeZone = websiteTimeZone; MinimumElasticInstanceCount = minimumElasticInstanceCount; AzureStorageAccounts = azureStorageAccounts; PublicNetworkAccess = publicNetworkAccess; }
public static IServiceCollection ConfigureCors(this IServiceCollection services, CorsSettings corsSettings, string policyName) { services.AddCors(options => { options.AddPolicy(policyName, corsBuilder => corsBuilder .WithOrigins(corsSettings.AllowedUrls.Split(";").Select(x => x.Trim()).ToArray()) .AllowAnyMethod().AllowAnyHeader().AllowCredentials() ); }); return(services); }