Ejemplo n.º 1
0
        private CorsConfiguration _GetCorsConfiguration()
        {
            var corsConfig = new CorsConfiguration();

            Configuration.GetSection("cors").Bind(corsConfig);
            return(corsConfig);
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ExperimentalToolLogger logger)
        {
            logger.LogExperimentMessage();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            CorsConfiguration corsConfiguration = new CorsConfiguration();

            Configuration.Bind(nameof(CorsConfiguration), corsConfiguration);
            if (!string.IsNullOrEmpty(corsConfiguration.AllowedOrigins))
            {
                app.UseCors(builder => builder.WithOrigins(corsConfiguration.GetOrigins()).AllowAnyHeader().AllowAnyMethod());
            }

            app.UseResponseCompression();
            app.UseMvc();
        }
Ejemplo n.º 3
0
        public static void Configure(this CorsPolicyBuilder builder, CorsConfiguration configuration)
        {
            if (configuration.AllowedOrigins == null)
            {
                builder.AllowAnyOrigin();
            }
            else
            {
                builder.WithOrigins(configuration.AllowedOrigins);
            }

            if (configuration.AllowedMethods == null)
            {
                builder.AllowAnyMethod();
            }
            else
            {
                builder.WithMethods(configuration.AllowedMethods);
            }

            if (configuration.AllowedHeaders == null)
            {
                builder.AllowAnyHeader();
            }
            else
            {
                builder.WithHeaders(configuration.AllowedHeaders);
            }
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            //configuração de CORS
            CorsConfiguration.UseCors(app);

            //configuração do JWT
            JwtConfiguration.UseJwt(app);

            //configuração do swagger
            SwaggerConfiguration.UseSwagger(app);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
 public static void EnableCors(this IPipelines pipelines, CorsConfiguration corsConfiguration)
 {
     pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
     {
         UpdateResponseHeaders(ctx.Request, ctx.Response, corsConfiguration);
     });
     pipelines.OnError.AddItemToEndOfPipeline((ctx, exception) =>
     {
         if (exception == null)
         {
             // Nothing to serialize, just return default 500 response
             return(HttpStatusCode.InternalServerError);
         }
         Response response;
         if (ctx.Request.Headers.Accept.Any(x => x.Item1.ToLowerInvariant().Contains("application/json")))
         {
             // Return the exception detail as JSON
             response = new JsonResponse(new ExceptionDetailObject(exception),
                                         new DefaultJsonSerializer())
             {
                 StatusCode = HttpStatusCode.InternalServerError
             };
         }
         else
         {
             // Return the exception message as text/plain
             response = new TextResponse(HttpStatusCode.InternalServerError, exception.Message);
         }
         UpdateResponseHeaders(ctx.Request, response, corsConfiguration);
         return(response);
     });
 }
        public void Should_prepend_attribute_policy_source()
        {
            var getActionContext = new ActionConfigurationContext(null,
                                                                  null, ActionMethod.From <CorsPolicySourceTests.Handler>(x => x.Get()), null);
            var postActionContext = new ActionConfigurationContext(null,
                                                                   null, ActionMethod.From <CorsPolicySourceTests.Handler>(x => x.Post()), null);
            var configuration = new CorsConfiguration();

            new CorsConfigurationDsl(configuration)
            .PrependPolicySource <CorsPolicySource>()
            .PrependAttributePolicySource(x => x.ActionMethod.Name == "Get");

            configuration.PolicySources.Count().ShouldEqual(2);

            var plugin = configuration.PolicySources.First();

            plugin.HasInstance.ShouldBeFalse();
            plugin.Type.ShouldEqual(typeof(CorsAttributePolicySource));
            plugin.AppliesTo(getActionContext).ShouldBeTrue();
            plugin.AppliesTo(postActionContext).ShouldBeFalse();

            plugin = configuration.PolicySources.Second();

            plugin.HasInstance.ShouldBeFalse();
            plugin.Type.ShouldEqual(typeof(CorsPolicySource));
            plugin.AppliesTo.ShouldBeNull();
        }
Ejemplo n.º 7
0
        public void Should_prepend_policy_source_plugin()
        {
            var getActionContext = new ActionConfigurationContext(null,
                                                                  null, ActionMethod.From <Handler>(x => x.Get()), null);
            var postActionContext = new ActionConfigurationContext(null,
                                                                   null, ActionMethod.From <Handler>(x => x.Post()), null);
            var overrideActionContext = new ActionConfigurationContext(null,
                                                                       null, ActionMethod.From <Handler>(x => x.Override()), null);
            var configuration = new CorsConfiguration();

            CorsPolicySource.PrependPolicy(configuration.PolicySources, x => x
                                           .PreflightMaxAge(1));
            CorsPolicySource.PrependPolicy(configuration.PolicySources, x => x
                                           .PreflightMaxAge(2)
                                           .AppliesWhen(a => a.ActionMethod.Name == "Get"));

            configuration.PolicySources.Count().ShouldEqual(2);

            var plugin = configuration.PolicySources.First();

            plugin.AppliesTo(getActionContext).ShouldBeTrue();
            plugin.AppliesTo(postActionContext).ShouldBeFalse();
            plugin.AppliesTo(overrideActionContext).ShouldBeFalse();
            plugin.Instance.CreatePolicy().PreflightMaxAge.ShouldEqual(2);

            plugin = configuration.PolicySources.Second();

            plugin.AppliesTo(getActionContext).ShouldBeTrue();
            plugin.AppliesTo(postActionContext).ShouldBeTrue();
            plugin.AppliesTo(overrideActionContext).ShouldBeFalse();
            plugin.Instance.CreatePolicy().PreflightMaxAge.ShouldEqual(1);
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Setup para configuração do Swagger
            SwaggerConfiguration.AddSwagger(services);

            //Setup para configuração do EntityFramework
            EntityFrameworkConfiguration.AddEntityFramework(services, Configuration);

            //Setup para configuração do JWT
            JwtConfiguration.ConfigureServices(services, Configuration);

            //Setup para o MongoDB
            MongoDBConfiguration.AddMongoDBSetup(services, Configuration);

            //Injeção de dependência
            DependencyInjectionConfiguration.AddDependencyInjection(services);

            //Setup para o MediatR
            MediatRConfiguration.AddMediatRSetup(services);

            //Setup para o AutoMapper
            AutoMapperConfiguration.AddAutoMapperSetup(services);

            //Setup para o CORS
            CorsConfiguration.AddCors(services);
        }
Ejemplo n.º 9
0
        public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment environment)
        {
            if (environment.IsDevelopment())
            {
                applicationBuilder.UseDeveloperExceptionPage();
            }
            else
            {
                applicationBuilder.UseHsts();
            }

            Configuration = ConfigurationBuilderConfiguration.Configure(applicationBuilder, environment);

            CorsConfiguration.Configure(applicationBuilder);
            SwaggerConfiguration.Configure(applicationBuilder);

            applicationBuilder
            .UseHttpsRedirection()
            .UseMvc()
            .Run(context =>
            {
                // Make the Swagger UI be the default when a Controller Action is not found
                context.Response.Redirect("swagger");
                return(Task.CompletedTask);
            });
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (AccessPolicies != null)
     {
         foreach (var element in AccessPolicies)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
     if (CosmosDbConfiguration != null)
     {
         CosmosDbConfiguration.Validate();
     }
     if (CorsConfiguration != null)
     {
         CorsConfiguration.Validate();
     }
     if (PrivateEndpointConnections != null)
     {
         foreach (var element1 in PrivateEndpointConnections)
         {
             if (element1 != null)
             {
                 element1.Validate();
             }
         }
     }
 }
Ejemplo n.º 11
0
        public static void ConfigureOAuth(HttpConfiguration config)
        {
            // Set up CORS configuration
            var corsConfig = new CorsConfiguration();

            corsConfig.AllowAll();

            var corsHandler = new CorsMessageHandler(corsConfig, config);

            config.MessageHandlers.Add(corsHandler);

            // Set up ACS token configuration
            var authenticationConfiguration = new AuthenticationConfiguration
            {
                RequireSsl = false,
                ClaimsAuthenticationManager = new ClaimsTransformer()
            };

            authenticationConfiguration.AddJsonWebToken(
                issuer: "https://eyecatch.accesscontrol.windows.net/",
                audience: "http://localhost:61390/",
                signingKey: "vZhjuby4hTmoaKnptAXe1MPAMiI+63obW20+fVaFAYM=",
                scheme: "ACS");

            config.MessageHandlers.Add(new AuthenticationHandler(authenticationConfiguration));
        }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <KorepetycjeContext>(options =>
                                                       options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
            KorepetycjeContext.ConnectionString = this.Configuration.GetConnectionString("DefaultConnection");

            SwaggerConfiguration.RegisterService(services);

            CorsConfiguration.Register(services,
                                       Configuration.GetSection(nameof(CorsConfigurationValues)).Get <CorsConfigurationValues>());

            services.AddIdentity <User, IdentityRole <int> >()
            .AddEntityFrameworkStores <KorepetycjeContext>()
            .AddDefaultTokenProviders();

            services.RegisterBearerPolicy(Configuration);

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddAutoMapper(); // Register AutoMapper

            RegisterServices(services);
            RegisterRepositories(services);
        }
        void ConfigureCors(CorsConfiguration corsConfig)
        {
            corsConfig
            .ForResources("~/Handler1.ashx")
            .ForOrigins("http://foo.com", "http://bar.com")
            .AllowAll();

            corsConfig
            .ForResources("~/Handler1.ashx")
            .ForOrigins("http://localhost")
            .AllowMethods("GET", "POST");

            corsConfig
            .ForResources("~/Handler2.ashx")
            .ForOrigins("http://localhost")
            .AllowMethods("GET", "POST")
            .AllowCookies()
            .AllowResponseHeaders("Foo");

            corsConfig
            .ForResources("~/Handler3.ashx")
            .ForOrigins("http://localhost")
            .AllowMethods("GET", "POST", "PUT")
            .AllowRequestHeaders("Content-Type");

            corsConfig
            .ForResources("~/Handler4.ashx")
            .ForOrigins("http://localhost")
            .AllowAllMethods()
            .AllowCookies()
            .AllowRequestHeaders("Content-Type", "Foo", "Authorization")
            .AllowResponseHeaders("Foo");
        }
Ejemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            DbContextConfiguration.AddService(services, Configuration);
            CorsConfiguration.AddService(services);
            RouteConfiguration.AddService(services);
            RouteAnalyzerExtension.AddService(services);
            services.AddMemoryCache();
            services.AddHttpContextAccessor();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            try
            {
                // TODO: when use code gen, a exception will occurred.
#pragma warning disable 618
                AuthenticationConfiguration.AddService(services, Configuration);
                services.AddAutoMapper();
#pragma warning disable 618
            }
            catch
            {
            }

            WebEncoderConfiguration.AddService(services);
            ValidateConfiguration.AddService(services);
            JsonExtension.AddService(services);
            SetCompatibilityVersionExtension.AddService(services);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (AccessPolicies == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "AccessPolicies");
     }
     if (AccessPolicies != null)
     {
         foreach (var element in AccessPolicies)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
     if (CosmosDbConfiguration != null)
     {
         CosmosDbConfiguration.Validate();
     }
     if (CorsConfiguration != null)
     {
         CorsConfiguration.Validate();
     }
 }
Ejemplo n.º 16
0
 public static void AddConfiguration(this IServiceCollection service)
 {
     DBConfiguration.Register(service);
     RepositoriesDI.Register(service);
     ServicesDI.Register(service);
     CorsConfiguration.RegisterCors(service);
     SwaggerConfiguration.RegisterSwagger(service);
 }
        public void Should_set_cors_engine_type()
        {
            var configuration = new CorsConfiguration();

            new CorsConfigurationDsl(configuration).WithEngine <CorsEngine>();

            configuration.CorsEngine.HasInstance.ShouldBeFalse();
            configuration.CorsEngine.Type.ShouldEqual(typeof(CorsEngine));
        }
Ejemplo n.º 18
0
 public void ConfigureServices(IServiceCollection services)
 {
     SimpleInjectorConfiguration.ConfigureServices(services, _configuration);
     CorsConfiguration.ConfigureServices(services);
     MvcConfiguration.ConfigureServices(services);
     SwaggerConfiguration.ConfigureServices(services);
     HangfireConfiguration.ConfigureServices(services, _configuration);
     DatabaseConfiguration.ConfigureServices(services, _configuration);
 }
        public void Should_set_cors_engine_instance()
        {
            var configuration = new CorsConfiguration();
            var engine        = new CorsEngine();

            new CorsConfigurationDsl(configuration).WithEngine(engine);

            configuration.CorsEngine.HasInstance.ShouldBeTrue();
            configuration.CorsEngine.Instance.ShouldEqual(engine);
        }
Ejemplo n.º 20
0
 public static void AddPolicies(this IServiceCollection services, CorsConfiguration corsConfig)
 {
     services.AddCors(
         options =>
     {
         foreach (var policy in corsConfig.Policies)
         {
             options.AddPolicy(policy.Name, builder => { AddPolicy(builder, policy); });
         }
     }
         );
 }
Ejemplo n.º 21
0
 { public static void ConfigureCorsService(IServiceCollection services, CorsConfiguration corsConfiguration)
   {
       services.AddCors(options => {
             options.AddPolicy(corsConfiguration.PolicyName, builder =>
                               builder.WithOrigins(corsConfiguration.Origins)
                               .AllowAnyHeader()
                               .AllowAnyMethod()
                               .AllowCredentials()
                               .SetPreflightMaxAge(TimeSpan.FromDays(14))
                               );
         });
   }
Ejemplo n.º 22
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            CorsConfiguration.Configure(app, Configuration);

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
        public void Should_configure_cors_policy_sources()
        {
            var configuration = new CorsConfiguration();

            new CorsConfigurationDsl(configuration).ConfigurePolicySources(x => x
                                                                           .Configure(c => c.Append <CorsPolicySource>()));

            configuration.PolicySources.Count().ShouldEqual(1);
            var plugin = configuration.PolicySources.First();

            plugin.HasInstance.ShouldBeFalse();
            plugin.Type.ShouldEqual(typeof(CorsPolicySource));
        }
Ejemplo n.º 24
0
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
     DatabaseConfiguration.Configure(app);
     LoggingConfiguration.Configure(app, _configuration, loggerFactory);
     RewriteConfiguration.Configure(app, env);
     SimpleInjectorConfiguration.Configure(app);
     CorsConfiguration.Configure(app, _configuration);
     MvcConfiguration.Configure(app, env);
     SwaggerConfiguration.Configure(app);
     AutoMapperConfiguration.Configure();
     FluentValidationConfiguration.Configure();
     HangfireConfiguration.Configure(app, _configuration);
 }
Ejemplo n.º 25
0
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

            _apiConfiguration = configuration
                                .GetSection(ApiConfiguration.SectionName)
                                .Get <ApiConfiguration>();
            _corsConfiguration = configuration
                                 .GetSection(CorsConfiguration.SectionName)
                                 .Get <CorsConfiguration>();

            _publicRoutes = _apiConfiguration.PublicRoutes?.ToHashSet() ?? new HashSet <string>();
        }
Ejemplo n.º 26
0
        public void ConfigureServices(IServiceCollection services)
        {
            BindConfiguration(services);
            CorsConfiguration.Configure(services);

            IMvcBuilder mvcBuilder = services
                                     .AddAutoMapper()
                                     .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            JsonFormattingConfiguration.Configure(mvcBuilder);

            DependencyInjectionConfiguration.Configure(services);
            SwaggerConfiguration.Configure(services);
        }
Ejemplo n.º 27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ExperimentalToolLogger logger,
            IAuthOptions options)
        {
            logger.LogExperimentMessage();
            if (options.KeyAuthenticationMode == KeyAuthenticationMode.NoAuth)
            {
                logger.LogNoAuthMessage();
            }
            else
            {
                //Auth is enabled and we are binding on http. Make sure we log a warning.

                string   hostingUrl = Configuration.GetValue <string>(WebHostDefaults.ServerUrlsKey);
                string[] urls       = ConfigurationHelper.SplitValue(hostingUrl);
                foreach (BindingAddress address in urls.Select(BindingAddress.Parse))
                {
                    if (string.Equals(Uri.UriSchemeHttp, address.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        logger.LogInsecureAuthMessage();
                        break;
                    }
                }
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseAuthorization();

            CorsConfiguration corsConfiguration = new CorsConfiguration();

            Configuration.Bind(nameof(CorsConfiguration), corsConfiguration);
            if (!string.IsNullOrEmpty(corsConfiguration.AllowedOrigins))
            {
                app.UseCors(builder => builder.WithOrigins(corsConfiguration.GetOrigins()).AllowAnyHeader().AllowAnyMethod());
            }

            app.UseResponseCompression();
            app.UseMvc();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Configures the services added to the container.
        /// </summary>
        /// <remarks>This method is called by asp.net core runtime.</remarks>
        /// <param name="services">The service collection.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            CorsConfiguration.ConfigureServices(services);

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
            .AddViewLocalization(options => options.ResourcesPath = "Resources")
            .AddDataAnnotationsLocalization();

            services.AddControllers();

            // Configure strongly typed settings objects
            var appSettingsSection = this.Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // Configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Security.JWT.Secret);

            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(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                };
            });

            // Configure DI for application services
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IUserPasswordResetTokenService, UserPasswordResetTokenService>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <IEmailTemplateService, EmailTemplateService>();
            services.AddScoped <ISpeechToTextService, SpeechToTextService>();
            services.AddScoped <IGroceryActionService, GroceryActionService>();
            services.AddScoped <IGroceryItemService, GroceryItemService>();
            services.AddScoped <IGroceryQuantityService, GroceryQuantityService>();
            services.AddScoped <IGroceryMeaninglessWordService, GroceryMeaninglessWordService>();
        }
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            LoggingConfiguration.ConfigureLogging(app, env, loggerFactory, Configuration);
            app.UseAuthentication();
            SwaggerConfiguration.AddSwagger(app);
            CorsConfiguration.UseCors(app);
            if (!env.IsDevelopment())
            {
                var context = app.ApplicationServices.GetService <PgsKanbanContext>();
                context.Database.Migrate();
            }

            SignalRConfiguration.UseSignalR(app);
            app.UseMvc();
        }
        public static void Register(HttpConfiguration config, IConfigurationRepository configurationRepository)
        {
            var corsConfiguration = new CorsConfiguration();

            corsConfiguration.AllowAll();
            var corsMessageHandler = new CorsMessageHandler(corsConfiguration, config);

            config.MessageHandlers.Add(corsMessageHandler);

            var authentication = CreateAuthenticationConfiguration(configurationRepository);
            //config.MessageHandlers.Add(new AuthenticationHandler(authentication));

            var authentificationhandler = new AuthenticationHandler(new IdentityServerHttpAuthentication(authentication, configurationRepository), config);

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{username}", new { username = RouteParameter.Optional }, null, authentificationhandler);
        }
 static UrlBasedCorsConfiguration()
 {
     Configuration = new CorsConfiguration();
 }
 public CorsMessageHandler(CorsConfiguration corsConfiguration, HttpConfiguration httpConfiguration)
 {
     this.corsConfiguration = corsConfiguration;
     this.httpConfiguration = httpConfiguration;
 }