public void Load(IServiceCollection services) { EnsureArg.IsNotNull(services, nameof(services)); var corsPolicyBuilder = new CorsPolicyBuilder() .WithOrigins(_corsConfiguration.Origins.ToArray()) .WithHeaders(_corsConfiguration.Headers.ToArray()) .WithMethods(_corsConfiguration.Methods.ToArray()); if (_corsConfiguration.MaxAge != null) { corsPolicyBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(_corsConfiguration.MaxAge.Value)); } if (_corsConfiguration.AllowCredentials) { corsPolicyBuilder.AllowCredentials(); } DefaultCorsPolicy = corsPolicyBuilder.Build(); services.AddCors(options => { options.AddPolicy( Constants.DefaultCorsPolicy, DefaultCorsPolicy); }); }
public async Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName) { var origin = context.Request.Headers["Origin"].Where(o => o.StartsWith("http", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (!origin.IsNullOrEmpty()) { var routeBinding = context.GetRouteBinding(); if (routeBinding != null && routeBinding.DownParty != null && (routeBinding.DownParty.Type == PartyTypes.OAuth2 || routeBinding.DownParty.Type == PartyTypes.Oidc)) { var party = await tenantRepository.GetAsync <OAuthDownParty>(routeBinding.DownParty.Id); if (party?.AllowCorsOrigins != null && party.AllowCorsOrigins.Count() > 0) { logger.ScopeTrace(() => $"Get CORS policy for origin '{origin}'."); var corsPolicyBuilder = new CorsPolicyBuilder(); corsPolicyBuilder.WithOrigins(party.AllowCorsOrigins.ToArray()) .AllowAnyHeader() .AllowAnyMethod(); corsPolicyBuilder.SetPreflightMaxAge(new TimeSpan(0, 0, settings.CorsPreflightMaxAge)); logger.ScopeTrace(() => "CORS policy added."); return(corsPolicyBuilder.Build()); } } } return(null); }
public static void SetupCors(this IServiceCollection services, IConfiguration configuration) { if (!configuration.GetValue <bool>("CorsEnabled")) { return; } var corsPolicies = configuration.GetSection("CorsPolicies"); if (corsPolicies.GetChildren().All(section => section.Key != KEYS_POLICY_NAME)) { services.AddCors(options => options.AddPolicy(KEYS_POLICY_NAME, builder => builder .AllowCredentials() .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() )); } foreach (var policyConfiguration in corsPolicies.GetChildren()) { var headers = policyConfiguration.GetSection("Headers").Value?.Split(','); var methods = policyConfiguration.GetSection("Methods").Value?.Split(','); var origins = policyConfiguration.GetSection("Origins").Value?.Split(','); var exposedHeaders = policyConfiguration.GetSection("ExposedHeaders").Value?.Split(','); if (methods == null || origins == null) { throw new InvalidOperationException( $"Missing configuration fields for {policyConfiguration.Key}, please specify Headers, Methods, Origins and ExposedHeaders"); } var policyBuilder = new CorsPolicyBuilder(origins); policyBuilder .WithHeaders(headers ?? new string[] { }) .WithMethods(methods) .WithExposedHeaders(exposedHeaders ?? new string[] { }); if (policyConfiguration.GetValue <bool>("AllowCredentials")) { policyBuilder.AllowCredentials(); } else { policyBuilder.DisallowCredentials(); } var maxPreflightAge = policyConfiguration.GetValue <double>("MaxPreflightAge"); if (maxPreflightAge != 0) { policyBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(maxPreflightAge)); } services.AddCors(options => options.AddPolicy(policyConfiguration.Key, policyBuilder.Build())); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddSingleton(_config); //services.AddStormpath(); // services.AddScoped<TokenProviderMiddleware>(); services.AddIdentity <ProductUser, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 4; config.Password.RequireDigit = true; config.Password.RequireNonAlphanumeric = true; // config.Cookies.ApplicationCookie.LoginPath }) .AddEntityFrameworkStores <ProductContext>(); services.AddLogging(); services.AddDbContext <ProductContext>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <ProductContext>(); //services.AddCors(options => options.AddPolicy("AllowAll", x => x.AllowAnyOrigin())); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:3000/")); }); // Define CORS Policy var corsBuilder = new CorsPolicyBuilder(); corsBuilder.WithHeaders("*"); corsBuilder.AllowAnyMethod(); corsBuilder.WithOrigins("http://localhost:3000"); //corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders().AllowAnyHeader(); corsBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(30)); services.AddCors(options => { options.AddPolicy("localhost", corsBuilder.Build()); }); // services.AddTransient<ProductContextSeedData>(); services.AddMvc(); }
public void SetPreFlightMaxAge_SetsThePreFlightAge() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.SetPreflightMaxAge(TimeSpan.FromSeconds(12)); // Assert var corsPolicy = builder.Build(); Assert.Equal(TimeSpan.FromSeconds(12), corsPolicy.PreflightMaxAge); }
private CorsPolicy Allow(string origin) { var policyBuilder = new CorsPolicyBuilder() .WithOrigins(origin) .AllowAnyHeader() .AllowAnyMethod(); if (_options.Cors.PreflightCacheDuration.HasValue) { policyBuilder.SetPreflightMaxAge(_options.Cors.PreflightCacheDuration.Value); } return(policyBuilder.Build()); }
/// <summary> /// BuildCorsPolicy /// </summary> public Task <CorsPolicy> BuildCorsPolicy(string origin) { var policy = new CorsPolicyBuilder() .WithOrigins(origin) .AllowAnyHeader() .AllowAnyMethod(); if (dynamicCorsOptions.PreflightCacheDuration != null) { policy.SetPreflightMaxAge(dynamicCorsOptions.PreflightCacheDuration.Value); } return(Task.FromResult(policy.Build())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { options.EnableEndpointRouting = false; }); services.AddHttpContextAccessor(); // Get client IP services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // Cors var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.SetPreflightMaxAge(TimeSpan.FromDays(1)); services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); // Add Swagger UI. services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\nExample: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "apiKey" }); c.OperationFilter <SwaggerAddHeaderParameter>(); var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swagger.xml"); c.IncludeXmlComments(filePath); c.CustomSchemaIds(x => x.FullName); }); services.AddMvc().SetCompatibilityVersion (CompatibilityVersion.Version_3_0); services.AddOptions(); services.AddMemoryCache(); services.Configure <IpRateLimitOptions> (Configuration.GetSection("IpRateLimit")); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>(); services.AddHttpContextAccessor(); }
internal override void Build() { if (string.IsNullOrWhiteSpace(ServiceName)) { throw new ArgumentException("ServiceName must be specified!"); } if (ServiceVersion == null) { throw new ArgumentException("ServiceVersion must be specified!"); } if (CorsAllowedHosts.Any() && !UseCors) { throw new ArgumentException("Set 'UseCors' to true if you want to specify AllowedHosts"); } if (SetupMassTransit) { Services.SetupMassTransitServices() .UseRabbitMqBusControl(rc => { rc.SetLogging(Configuration[SerilogElasticEndpoint], Configuration[SerilogIndexFormat], Configuration[SerilogElasticPassword], Configuration[SerilogLogLevel]); rc.Durable(true); rc.SetCredentials(Configuration[RabbitMqUserConfig], Configuration[RabbitMqPasswordConfig]); rc.SetHost(Configuration[RabbitMqHostConfig]); rc.SetExchangeType(ExchangeType.Fanout); if (SetupDefaultReceiveEndpoint) { rc.AddReceiveEndpoint(ServiceName, c => { // Make copy var assemblies = new[] { Assembly.GetEntryAssembly() }; c.AddConsumersInheritingFrom <IConsumer>(assemblies.ToArray()); }); } foreach (var endpointDefinition in _receiveEndpointDefinitions) { rc.AddReceiveEndpoint(endpointDefinition); } rc.Durable(true); }); } if (UseDefaultSwaggerSetup) { Services.SetupSwaggerServices(sc => { sc.Version(ServiceVersion); sc.IncludeXmlComments(); sc.Title(ServiceName); }); } if (UseCors) { var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.SetIsOriginAllowed(origin => CorsAllowedHosts.Contains(origin)); corsBuilder.AllowCredentials(); corsBuilder.SetPreflightMaxAge(TimeSpan.FromDays(1)); Services.AddCors(options => { options.AddPolicy("HelperAllowedHosts", corsBuilder.Build()); }); } if (UseJwtAuthentication) { // Authentication Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.Audience = Configuration[JwtAudienceConfig]; cfg.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidAudience = Configuration[JwtAudienceConfig], ValidateIssuer = true, ValidIssuer = Configuration[JwtIssuerConfig], ClockSkew = TimeSpan.FromMinutes(2), IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[JwtSigningKeyConfig])) }; }); } }