Example #1
0
 protected virtual void ConfigureCors(CorsPolicyBuilder builder)
 {
     builder.AllowAnyHeader();
     builder.AllowAnyMethod();
     builder.AllowCredentials();
     builder.SetIsOriginAllowed(args => true);
 }
 private static void ConfigureCorsUsage(CorsPolicyBuilder builder)
 {
     builder
     .SetIsOriginAllowed(_ => true)
     .AllowAnyHeader()
     .AllowAnyMethod()
     .AllowCredentials();
 }
 void DevelopmentCorsPolicy(CorsPolicyBuilder builder)
 {
     builder.SetIsOriginAllowed(origin =>
     {
         return(new Uri(origin).Host == "localhost");
     })
     .AllowAnyMethod()
     .AllowAnyHeader()
     .AllowCredentials();
 }
Example #4
0
    public void SetIsOriginAllowed_AddsIsOriginAllowed()
    {
        // Arrange
        var builder = new CorsPolicyBuilder();
        Func <string, bool> isOriginAllowed = origin => true;

        // Act
        builder.SetIsOriginAllowed(isOriginAllowed);

        // Assert
        var corsPolicy = builder.Build();

        Assert.Same(corsPolicy.IsOriginAllowed, isOriginAllowed);
    }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;

            services.AddDbContext <ApiContext>(opt => opt.UseSqlite("Data Source=StockManagement.db;"));

            // Validation rules

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation();

            var mappingConfig = new MapperConfiguration(mc =>
            {
                {
                    mc.CreateMissingTypeMaps = false;
                    mc.AddProfile(new MappingProfiles());
                }
            });

            // Set Adapter pattern
            var mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            ConfigureJwt(services);

            var ded = new ConfigureDependencies();

            ded.ConfigureRepositories(services);
            ded.ConfigureServices(services);

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "StockManagement API",
                    Description = "StockManagement API"
                });
            });

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.SetIsOriginAllowed(host => true);
            corsBuilder.AllowCredentials();

            services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); });
        }
Example #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddRouting(options => options.LowercaseUrls = true);
            services.AddControllers()
            .AddJsonOptions(ops =>
            {
                ops.JsonSerializerOptions.WriteIndented        = true;
                ops.JsonSerializerOptions.IgnoreNullValues     = true;
                ops.JsonSerializerOptions.DictionaryKeyPolicy  = JsonNamingPolicy.CamelCase;
                ops.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            })
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                               );


            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });
            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "RepositoryPattern", Version = "v1"
                }); });

            var corsBuilder = new CorsPolicyBuilder();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  corsBuilder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().Build());
            });

            // DB stuff
            services.AddDbContext <AppDbContext>(ServiceLifetime.Singleton);
            services.AddSingleton <IUnitOfWork, UnitOfWork>();
            services.AddSingleton <IDataSource, AppDbContext>();

            // register services
            services.AddSingleton <IDeveloperService, DeveloperService>();
            services.AddSingleton <IProjectService, ProjectService>();
        }
        public static IServiceCollection AddElectCors(this IServiceCollection services,
                                                      [NotNull] Action <ElectCorsOptions> configuration)
        {
            services.Configure(configuration);

            var options = configuration.GetValue();

            var corsBuilder = new CorsPolicyBuilder();

            if (options.IsOriginAllowed != null)
            {
                corsBuilder.SetIsOriginAllowed(options.IsOriginAllowed);
            }
            else if (options.AllowOrigins?.Any() == true)
            {
                options.AllowOrigins = options.AllowOrigins.Distinct().OrderBy(x => x).ToList();

                if (options.AllowOrigins.Contains("*"))
                {
                    corsBuilder.SetIsOriginAllowed((origin) => true);
                }
                else
                {
                    corsBuilder.WithOrigins(options.AllowOrigins.ToArray());
                    corsBuilder.SetIsOriginAllowedToAllowWildcardSubdomains();
                }
            }


            if (options.AllowHeaders?.Any() == true)
            {
                if (options.AllowHeaders.Contains("*"))
                {
                    corsBuilder.AllowAnyHeader();
                }
                else
                {
                    corsBuilder.WithHeaders(options.AllowHeaders.ToArray());
                }
            }

            if (options.AllowMethods?.Any() == true)
            {
                if (options.AllowMethods.Contains("*"))
                {
                    corsBuilder.AllowAnyMethod();
                }
                else
                {
                    corsBuilder.WithMethods(options.AllowMethods.ToArray());
                }
            }

            if (options.IsAllowCredentials)
            {
                corsBuilder.AllowCredentials();
            }
            else
            {
                corsBuilder.DisallowCredentials();
            }

            options.ExtendPolicyBuilder?.Invoke(corsBuilder);

            services.AddCors(config =>
            {
                config.DefaultPolicyName = options.PolicyName;

                config.AddDefaultPolicy(corsBuilder.Build());

                options.ExtendPolicyOptions?.Invoke(config);
            });

            services.Configure <MvcOptions>(config =>
            {
                config.Filters.Add(new CorsAuthorizationFilterFactory(options.PolicyName));
            });

            services.TryAddTransient <CorsAuthorizationFilter, CorsAuthorizationFilter>();

            return(services);
        }
Example #8
0
        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]))
                    };
                });
            }
        }