public void SimpleRequestDoNotAllowCredentials() { CorsConfig config = CorsConfigBuilder.ForAnyOrigin().Build(); IHttpResponse response = SimpleRequest(config, "http://localhost:7777"); Assert.False(response.Headers.Contains(HttpHeaderNames.AccessControlAllowCredentials)); }
public void SimpleRequestAllowCredentials() { CorsConfig config = CorsConfigBuilder.ForAnyOrigin().AllowCredentials().Build(); IHttpResponse response = SimpleRequest(config, "http://localhost:7777"); Assert.Equal("true", response.Headers.Get(HttpHeaderNames.AccessControlAllowCredentials, null)); }
protected void Application_Start() { AutoMapper.Mapper.AddProfile <IndexMappingProfile>(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); CorsConfig.RegisterCors(UrlBasedCorsConfiguration.Configuration); // Create the container builder. var builder = new ContainerBuilder(); builder.RegisterModule(new ApplicationModule()); // Register the Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Build the container. var container = builder.Build(); // Create the depenedency resolver. var resolver = new AutofacWebApiDependencyResolver(container); // Configure Web API with the dependency resolver. GlobalConfiguration.Configuration.DependencyResolver = resolver; }
public static void AddCorsPolicies(this IServiceCollection services, IConfiguration configuration) { _corsConfig = configuration.GetSection(nameof(CorsConfig)).Get <CorsConfig>(); services.AddCors(x => { x.AddPolicy("development", builder => { builder .AllowAnyOrigin() .WithHeaders("authorization", "content-type", "x-ms-command-name") .AllowAnyMethod(); }); x.AddPolicy("production", builder => { if (_corsConfig.AllowedOrigins.Length > 0) { builder.WithOrigins(_corsConfig.AllowedOrigins); } else { builder.AllowAnyOrigin(); } builder .WithHeaders(_corsConfig.AllowedHeaders) .AllowAnyMethod(); }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IocRegister.AddRegistration(services, Configuration); SwaggerConfig.AddRegistration(services); CorsConfig.AddCorsOptions(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public static void AddCorsPolicies(this IServiceCollection services, CorsConfig config) { services.AddCors(x => { x.AddPolicy("development", builder => { builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); x.AddPolicy("production", builder => { builder.WithOrigins(config.Origins.ToArray()) .WithMethods(config.Headers.ToArray()) .AllowAnyMethod(); if (!config.AllowCredentials) { builder.DisallowCredentials(); return; } builder.AllowCredentials(); }); }); }
public static void AddCors(this IServiceCollection services, IConfiguration configuration) { var corsConfig = new CorsConfig(configuration); if (string.IsNullOrWhiteSpace(corsConfig.Name)) { return; } services.AddCors( options => options.AddPolicy( corsConfig.Name, corsBuilder => { var builder = corsBuilder .WithOrigins(corsConfig.AllowedOrigins) .WithHeaders(corsConfig.AllowedHeaders) .WithMethods(corsConfig.AllowedMethods) .WithExposedHeaders(corsConfig.ExposedHeaders); if (corsConfig.AllowCredentials) { builder.AllowCredentials(); } else { builder.DisallowCredentials(); } builder.Build(); })); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { CorsConfig.Use_CorsConfig_App(app); app.UseMvc(); SwaggerConfig.Use_SwaggerConfigApp(app); app.UseRabbitListener(); }
public void Origin() { CorsConfig cors = CorsConfigBuilder.ForOrigin((StringCharSequence)"http://localhost:7888").Build(); Assert.Equal("http://localhost:7888", cors.Origin.ToString()); Assert.False(cors.IsAnyOriginSupported); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var corsConfig = new CorsConfig(); this.Configuration.Bind(corsConfig); app.UseCors(builder => builder .WithOrigins(corsConfig.ALLOWED_ORIGINS.Split(new[] { "~", "," }, StringSplitOptions.RemoveEmptyEntries)) .AllowAnyHeader().AllowAnyMethod()); app.UseAuthentication(); app.UseMvc(); app.UseGraphQL <ISchema>(Routes.Query); if (env.IsDevelopment()) { app.UseGraphQLPlayground(new GraphQLPlaygroundOptions { Path = Routes.Playground, GraphQLEndPoint = Routes.Query }); } }
public void ShortCircuit() { CorsConfig cors = CorsConfigBuilder.ForOrigin((AsciiString)"http://localhost:8080") .ShortCircuit().Build(); Assert.True(cors.IsShortCircuit); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseWebSockets(); app.UseHttpsRedirection(); app.UseMvc(); // JWT JwtAuthConfig.AddRegistration(app, this._configuration); // Cors CorsConfig.AddRegistration(app); //GraphQL GraphQLConfig.AddRegistration(app); }
public void DefaultPreflightResponseHeaders() { CorsConfig cors = CorsConfigBuilder.ForAnyOrigin().Build(); Assert.NotNull(cors.PreflightResponseHeaders().Get(HttpHeaderNames.Date, null)); Assert.Equal("0", cors.PreflightResponseHeaders().Get(HttpHeaderNames.ContentLength, null)); }
public void PreflightResponseHeadersSingleValue() { CorsConfig cors = CorsConfigBuilder.ForAnyOrigin() .PreflightResponseHeader((AsciiString)"SingleValue", (StringCharSequence)"value").Build(); Assert.Equal((AsciiString)"value", cors.PreflightResponseHeaders().Get((AsciiString)"SingleValue", null)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseHttpsRedirection(); } app.UseHealthChecks("/api/health"); app.UseMetricServer(); app.UseRequestMiddleware(); app.UseAuthentication(); StartupDatabaseInitializer.MigrateDatabase(app); APIDocumentationInitializer.AllowAPIDocumentation(app); CorsConfig.AddCors(app); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } CorsConfig.UseCors(app); _ = new src.Shared.ConexionManager(); app.UseHttpsRedirection(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // (c => //{ // c.RouteTemplate = "api/swagger/{documentname}/swagger.json"; //}); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "GolkiiAPI V1"); c.RoutePrefix = "api/docs"; }); app.UseMvc(); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddHealthChecks(); services.AddSwaggerGen(c => { var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"); c.IncludeXmlComments(xmlPath); }); services.AddAuthZeroConfig(Configuration); services.AddCors(CorsConfig.GetPolicy()); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddTransient <IApiKey, GoogleLocationApiKey>(); services.AddHttpClient <GeocodingService>() .AddPolicyHandler(PollyConfig.GetRetryPolicy()) .AddPolicyHandler(PollyConfig.GetCircuitBreakerPolicy()); services.AddDbContext <WorkerDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("WorkerDatabase"))); services.AddScoped <IWorkerRepository, WorkerRepository>(); services.AddTransient <IAddressToCoordinatesTranslator, AddressToCoordinatesTranslator>(); services.AddTransient <DistanceCalculator>(); services.AddTransient <WorkerProfileFinder>(); services.AddSpaStaticFiles(SpaConfig.GetOptions()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Set compability mode for mvc services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); services.AddSingleton <ITracer>(serviceProvider => { var serviceName = Assembly.GetEntryAssembly().GetName().Name; Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName + "-http"); var loggerFactory = new LoggerFactory(); try { // add agenthost and port var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); } catch (Exception) { Console.WriteLine("Couldn't register logger"); } return(null); }); services.AddHttpClient(); //services.AddLogging (loggingBuilder => loggingBuilder.AddSerilog (dispose: true)); services.AddOpenTracing(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidAudience = "auth", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppSettings:Secret"])) }; }); APIDocumentationInitializer.ApiDocumentationInitializer(services); StartupDatabaseInitializer.InitializeDatabase(services); services.AddHealthChecks(); CorsConfig.AddCorsPolicy(services); }
public void PreflightRequestDoNotAllowCredentials() { CorsConfig config = CorsConfigBuilder.ForOrigin((AsciiString)"http://localhost:8888").Build(); IHttpResponse response = PreflightRequest(config, "http://localhost:8888", ""); // the only valid value for Access-Control-Allow-Credentials is true. Assert.False(response.Headers.Contains(HttpHeaderNames.AccessControlAllowCredentials)); }
public void WildcardOrigin() { CorsConfig cors = CorsConfigBuilder.ForOrigin(CorsHandler.AnyOrigin).Build(); Assert.True(cors.IsAnyOriginSupported); Assert.Equal("*", cors.Origin.ToString()); Assert.Equal(0, cors.Origins.Count); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Set compability mode for mvc services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); CorsConfig.AddCorsPolicy(services); services.AddOcelot(Configuration); }
public void ExposeHeaders() { CorsConfig cors = CorsConfigBuilder.ForAnyOrigin() .ExposeHeaders((StringCharSequence)"custom-header1", (StringCharSequence)"custom-header2").Build(); Assert.True(cors.ExposedHeaders().Contains((StringCharSequence)"custom-header1")); Assert.True(cors.ExposedHeaders().Contains((StringCharSequence)"custom-header2")); }
/// <summary> /// 配置跨域 /// </summary> /// <param name="app"></param> /// <param name="config"></param> public static void UserCorsMiddleware(this IApplicationBuilder app, CorsConfig config) { if (!config.Enable) { return; } app.UseCors(config.PolicyName);//配置跨域策略 }
public void RequestMethods() { CorsConfig cors = CorsConfigBuilder.ForAnyOrigin() .AllowedRequestMethods(HttpMethod.Post, HttpMethod.Get).Build(); Assert.True(cors.AllowedRequestMethods().Contains(HttpMethod.Post)); Assert.True(cors.AllowedRequestMethods().Contains(HttpMethod.Get)); }
public static void ConfigureCors(this IApplicationBuilder app, CorsConfig corsConfig) { app.UseCors(corsConfig.CorsPolicy); app.UseCors(builder => builder.WithOrigins(corsConfig.AllowedCorsDomains) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }
protected void Application_Start(object sender, EventArgs e) { IocConfig.RegisterDependencyResolver(GlobalConfiguration.Configuration); WebApiConfig.Register(GlobalConfiguration.Configuration); DtoMapperConfig.CreateMaps(); CorsConfig.RegisterCors(GlobalConfiguration.Configuration); }
public void RequestHeaders() { CorsConfig cors = CorsConfigBuilder.ForAnyOrigin() .AllowedRequestHeaders((AsciiString)"preflight-header1", (AsciiString)"preflight-header2").Build(); Assert.True(cors.AllowedRequestHeaders().Contains((AsciiString)"preflight-header1")); Assert.True(cors.AllowedRequestHeaders().Contains((AsciiString)"preflight-header2")); }
public void SimpleRequestNoShortCircuit() { CorsConfig config = CorsConfigBuilder.ForOrigin((AsciiString)"http://localhost:8080").Build(); IHttpResponse response = SimpleRequest(config, "http://localhost:7777"); Assert.Equal(HttpResponseStatus.OK, response.Status); Assert.Null(response.Headers.Get(HttpHeaderNames.AccessControlAllowOrigin, null)); }
public void PreflightRequestAllowCredentials() { var origin = new AsciiString("null"); CorsConfig config = CorsConfigBuilder.ForOrigin(origin).AllowCredentials().Build(); IHttpResponse response = PreflightRequest(config, origin.ToString(), "content-type, xheader1"); Assert.Equal("true", response.Headers.Get(HttpHeaderNames.AccessControlAllowCredentials, null)); }
public void PreflightRequestWithUnauthorizedOrigin() { var origin = "http://host"; CorsConfig config = CorsConfigBuilder.ForOrigin((AsciiString)"http://localhost").Build(); var response = PreflightRequest(config, origin, "xheader1"); Assert.False(response.Headers.Contains(HttpHeaderNames.AccessControlAllowOrigin)); Assert.True(ReferenceCountUtil.Release(response)); }
private static void Clean(CorsConfig cs) { PropertyInfo[] properties = cs.GetType().GetProperties(); foreach (var p in properties) { object valobj = p.GetValue(cs); if (valobj != null && valobj.GetType().Equals(typeof(string))) { string val = (string)valobj; if (!string.IsNullOrEmpty(val)) { val = val.Replace(" ", ""); p.SetValue(cs, val); } } } }