Beispiel #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //Add CORS support.
            // Must be first to avoid OPTIONS issues when calling from Angular/Browser
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("allReady", corsBuilder.Build());
            });

            // Add Application Insights data collection services to the services container.
            services.AddApplicationInsightsTelemetry(Configuration);

            // Add Entity Framework services to the services container.
            services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage"));
            services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection"));
            services.Configure<EmailSettings>(Configuration.GetSection("Email"));
            services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData"));
            services.Configure<GeneralSettings>(Configuration.GetSection("General"));
            services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter"));

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 10;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = true;
                options.Password.RequireUppercase = false;
                options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
            })
            .AddEntityFrameworkStores<AllReadyContext>()
            .AddDefaultTokenProviders();

            // Add Authorization rules for the app
            services.AddAuthorization(options =>
            {
                options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin"));
                options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin"));
            });

            // Add MVC services to the services container.
            // config add to get passed Angular failing on Options request when logging in.
            services.AddMvc().AddJsonOptions(options =>
                options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            //Hangfire
            services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"]));

            // configure IoC support
            var container = CreateIoCContainer(services);
            return container.Resolve<IServiceProvider>();
        }
        public void AllowAnyHeaders_AllowsAny()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.AllowAnyHeader();

            // Assert
            var corsPolicy = builder.Build();
            Assert.True(corsPolicy.AllowAnyHeader);
            Assert.Equal(new List<string>() { "*" }, corsPolicy.Headers);
        }
        /// <summary>
        /// Setups the cors.
        /// </summary>
        /// <param name="services">The services.</param>
        public static void SetupCors(this IServiceCollection services)
        {
            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();             // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")));

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:8080");

            services.AddCors(options =>
            {
                options.AddPolicy(CorsOrigins, corsBuilder.Build());
            });
        }
Beispiel #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.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 https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddControllers();
            services.AddSwaggerGen();

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.

            corsBuilder.AllowCredentials();
        }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddTransient <ISubmissionToDatabase, SubmissionToDatabase>();
            services.AddTransient <ISubmissionsMiddle, SubmissionsMiddle>();
            services.AddTransient <IMongoClient, MongoClient>();

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });
            services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddEntityFrameworkNpgsql().AddDbContext<MMIAssessDbContext>(dbOptions =>
            //    dbOptions.UseNpgsql(Configuration.GetConnectionString("AppDBConnectionString"))
            //);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", corsBuilder.Build());
            });
        }
Beispiel #9
0
        public CorsPolicy Build()
        {
            CorsPolicyBuilder policy = new CorsPolicyBuilder();

            if (this.AllowAnyOrigin)
            {
                policy.AllowAnyOrigin();
            }
            else
            {
                policy.WithOrigins(this.Origins);
            }

            if (this.AllowAnyHeader)
            {
                policy.AllowAnyHeader();
            }
            else
            {
                policy.WithHeaders(this.Headers);
            }

            if (this.AllowAnyMethod)
            {
                policy.AllowAnyMethod();
            }
            else
            {
                policy.WithMethods(this.Methods);
            }

            if (this.SupportsCredentials)
            {
                policy.AllowCredentials();
            }
            else
            {
                policy.DisallowCredentials();
            }

            policy.WithExposedHeaders("content-disposition");

            return(policy.Build());
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();                                            // For anyone access.
            corsBuilder.WithOrigins("https://localhost:82");                         // for a specific url. Don't add a forward slash on the end!
            corsBuilder.WithOrigins("http://localhost:65182");                       // for a specific url. Don't add a forward slash on the end!
            corsBuilder.WithOrigins("https://addresstranslation.azurewebsites.net"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            //services.AddCors( options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://atservicetest.azurewebsites.net", "https://addresstranslation.azurewebsites.net"); }); });

            new GetConnectionString().getconnection(Configuration);

            //  services.Add(new ServiceDescriptor(typeof(LoginContext), new LoginContext(Configuration.GetConnectionString("DefaultConnection"))));
            //  services.Add(new ServiceDescriptor(typeof(HomeContext), new HomeContext(Configuration.GetConnectionString("DefaultConnection"))));
            //  services.Add(new ServiceDescriptor(typeof(LoginDataContext), new LoginDataContext(Configuration.GetConnectionString("DefaultConnection"))));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info {
                    Title = "Core API", Description = "Swagger Core API"
                });
            }

                                   );

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Beispiel #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IItemService, ItemService>();
            services.AddMvc().AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddDbContext <SCMSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SCMS")));

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
        /// <summary>
        /// Customizes cors cfg
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static CorsPolicyBuilder CustomizeCors(this CorsPolicyBuilder builder)
        {
            var cfg = Cartomatic.Utils.NetCoreConfig.GetNetCoreConfig();

            var origins = cfg.GetSection("CorsCfg:Origins").Get <string[]>() ?? new string[0];
            var headers = cfg.GetSection("CorsCfg:Headers").Get <string[]>() ?? new string[0];
            var methods = cfg.GetSection("CorsCfg:Methods").Get <string[]>() ?? new string[0];

            //all origins allowed
            if (origins.Any(o => o == "*"))
            {
                builder.AllowAnyOrigin();
            }
            else if (origins.Any())
            {
                if (origins.Any(o => o.IndexOf("*") > -1))
                {
                    builder.SetIsOriginAllowedToAllowWildcardSubdomains();
                }

                builder.WithOrigins(origins);
            }

            if (headers.Any(h => h == "*"))
            {
                builder.AllowAnyHeader();
            }
            else if (headers.Any())
            {
                builder.WithHeaders(headers);
            }

            if (methods.Any(m => m == "*"))
            {
                builder.AllowAnyMethod();
            }
            else if (methods.Any())
            {
                builder.WithMethods(methods);
            }

            return(builder);
        }
Beispiel #13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddTransient <IQuestionsRepository, QuestionsRepository>();

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddDataProtection()
            .PersistKeysToFileSystem(GetKeyRingDirInfo())
            .SetApplicationName("SharedCookieApp");

            services.ConfigureApplicationCookie(options => {
                options.Cookie.Name = ".AspNet.SharedCookie";
            });

            #region CROS
            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://*****:*****@"Server=(localdb)\mssqllocaldb;Database=es5;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext <TestContext>(options => options.UseSqlServer(connection));
        }
        public void Configure(CorsOptions options)
        {
            if (_env.IsLinuxConsumption())
            {
                string[] allowedOrigins = _hostCorsOptions.Value.AllowedOrigins?.ToArray() ?? Array.Empty <string>();
                var      policyBuilder  = new CorsPolicyBuilder(allowedOrigins);

                if (_hostCorsOptions.Value.SupportCredentials)
                {
                    policyBuilder = policyBuilder.AllowCredentials();
                }

                policyBuilder.AllowAnyHeader();
                policyBuilder.AllowAnyMethod();

                var policy = policyBuilder.Build();
                options.AddDefaultPolicy(policy);
            }
        }
Beispiel #15
0
            public static void Service(IServiceCollection services)
            {
                var corsBuilder = new CorsPolicyBuilder();

                corsBuilder.AllowAnyOrigin();
                corsBuilder.AllowAnyHeader();
                corsBuilder.AllowAnyMethod();
                corsBuilder.AllowCredentials();

                services.AddCors(options =>
                {
                    options.AddPolicy(Core.SystemConfigs.Server.Cros.PolicyAllowAllName, corsBuilder.Build());
                });

                services.Configure <MvcOptions>(options =>
                {
                    options.Filters.Add(new CorsAuthorizationFilterFactory(Core.SystemConfigs.Server.Cros.PolicyAllowAllName));
                });
            }
Beispiel #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=.;Database=Usuarios;Trusted_Connection=True;";

            services.AddDbContext <UsuariosContext>(options => options.UseSqlServer(connection));
            // Add framework services.
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", corsBuilder.Build());
            });
            services.AddMvc();
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
            services.AddMvc();

            var connection = $"{Configuration["ConnectionStrings:EntityFramework"]}";

            services.AddDbContext <MainContext>(options => options.UseSqlServer(connection));

            // helpers
            services.AddTransient <IDateTimeProvider, DateTimeProvider>();

            // modules (always repo first, then service etc.)
            services.AddTransient <IProductStateRepository, MainRepository>();
            services.AddTransient <IProductService, ProductService>();

            services.AddTransient <IProjectStateRepository, MainRepository>();
            services.AddTransient <IProjectService, ProjectService>();

            services.AddTransient <IContactStateRepository, MainRepository>();
            services.AddTransient <IContactService, ContactService>();

            services.AddTransient <ICompanyStateRepository, MainRepository>();
            services.AddTransient <ICompanyService, CompanyService>();

            services.AddTransient <IEmploymentStateRepository, MainRepository>();
            services.AddTransient <IEmploymentService, EmploymentService>();

            services.AddTransient <ICommandStateRepository, MainRepository>();
            services.AddTransient <ICommandManager, CommandManager>();
        }
Beispiel #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton <IPublisher, ReceiptPublisher>();
            services.AddSignalR();

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.WithOrigins("http://localhost:6001", "https://fticlient.azurewebsites.net", "http://localhost:4200");
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", corsBuilder.Build());
            });
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:5000");
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("AureliaSPA", corsBuilder.Build());
            });

            // Add framework services.
            services.AddMvc();

            //DI
            services.AddSingleton <IDroidRepository, DroidRepository>();
        }
Beispiel #20
0
        public void ConfigureServices(IServiceCollection services)
        {
            //Config
            var cfgBuilder = new ConfigurationBuilder()
                             .SetBasePath(env.ContentRootPath)
                             .AddJsonFile("appsettings.json");
            IConfigurationRoot configuration = cfgBuilder.Build();

            services.Configure <VouchersConfig>(configuration);
            services.AddSingleton(typeof(IConfigurationRoot), configuration);
            string conStr = configuration["ConnectionStrings:SQLServerDBConnection"];

            //EF
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <VouchersDBContext>(options => options.UseSqlServer(conStr));
            services.AddScoped <IVouchersRepository, VouchersRepository>();

            //CORS
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            // For specific URL
            // corsBuilder.WithOrigins("http://localhost:4200")
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            //Serialization Options
            services.AddMvc().AddJsonOptions(ser =>
            {
                ser.SerializerSettings.ContractResolver =
                    new DefaultContractResolver();
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <SistemaDeRestauranteContext>(options => options.UseSqlServer(connection, b => b.MigrationsAssembly("API")));
            services.AddMvc();

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();

            services.AddDbContext <RecruitmentMDbContext>(options =>
                                                          options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddScoped <IApplicantService, ApplicantService>();
            services.AddScoped <IApplicantRepository, ApplicantRepository>();

            services.AddScoped <IExperienceService, ExperienceService>();
            services.AddScoped <IWorkflowService, WorkflowService>();
            services.AddScoped <IApplicantWorkflowService, ApplicantWorkflowService>();

            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));

            services.AddMvc();

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Recruitment API", Version = "v1"
                });
            });
        }
Beispiel #23
0
        public void ConfigureServices(IServiceCollection services)
        {
            //Config
            var cfgBuilder = new ConfigurationBuilder()
                             .SetBasePath(env.ContentRootPath)
                             .AddJsonFile("appsettings.json");
            var configuration = cfgBuilder.Build();

            //Weak Typed
            var conStr = configuration["ConnectionStrings:LocalDBConnection"];

            //Strong Typed
            services.Configure <VouchersConfig>(configuration);

            //CORS
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            // For specific URL
            // corsBuilder.WithOrigins("http://localhost:4200")
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            //Serialization Options
            services.AddMvc().AddJsonOptions(ser =>
            {
                ser.SerializerSettings.ContractResolver =
                    new DefaultContractResolver();
            });

            services.AddMvc();
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(
                options =>
            {
                options.SslPort = 44321;
                options.Filters.Add(new RequireHttpsAttribute());
            }
                ).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            // services.AddCors( options => {
            //     options.AddPolicy("AllowSpecificOrigin", builder =>
            //     {
            //         // "https://192.168.1.13:8080", "http://192.168.1.13:8080",
            //         builder.WithOrigins(
            //         "http://192.168.1.6:8080", "https://192.168.1.6:8080",
            //         "http://localhost:8080", "https://localhost:8080");
            //     });
            // });
            services.AddAntiforgery(
                options =>
            {
                options.Cookie.Name         = "_af";
                options.Cookie.HttpOnly     = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.HeaderName          = "X-XSRF-TOKEN";
            }
                );

            // TODO 需设置合适的CORS策略
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            //The CORS protocol does not allow specifying a wildcard (any) origin
            //and credentials at the same time. Configure the policy by listing individ
            // corsBuilder.AllowCredentials();

            services.AddCors(options => {
                options.AddPolicy("AllowAnyOrigin", corsBuilder.Build());
            });
        }
 // This method gets called by the runtime. Use this method to add services to the container
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     // ********************
     // Setup CORS
     // ********************
     var corsBuilder = new CorsPolicyBuilder();
     corsBuilder.AllowAnyHeader();
     corsBuilder.AllowAnyMethod();
     corsBuilder.AllowAnyOrigin(); // For anyone access.
     //corsBuilder.WithOrigins("http://localhost:12345"); // for a specific url. Don't add a forward slash on the end!
     corsBuilder.AllowCredentials();
     services.AddCors(options =>
     {
         options.AddPolicy("<YourCorsPolicyName>", corsBuilder.Build());
     });
     var xmlPath = GetXmlCommentsPath();
     // Register the Swagger generator, defining one or more Swagger documents
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("v1", new Info { Title = "XYZ API", Version = "v1", Description = "This is a API for XYZ client applications.", });
         c.IncludeXmlComments(xmlPath);
         c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { In = "header", Description = "Please paste JWT Token with Bearer + White Space + Token into field", Name = "Authorization", Type = "apiKey" });
     });
     // Add framework services.
     services.AddOptions();
     // Use policy auth.
     services.AddAuthorization(options =>
     {
         options.AddPolicy("AuthorizationPolicy",
                           policy => policy.RequireClaim("DeveloperBoss", "IAmBoss"));
     });
     // Get options from app settings
     var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
     // Configure JwtIssuerOptions
     services.Configure<JwtIssuerOptions>(options =>
     {
         options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
         options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
         options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
     });
 }
Beispiel #26
0
        public CorsPolicy Build()
        {
            var policy = new CorsPolicyBuilder();

            if (this.AllowAnyOrigin)
            {
                policy.AllowAnyOrigin();
            }
            else
            {
                policy.WithOrigins(this.Origins);
            }

            if (this.AllowAnyHeader)
            {
                policy.AllowAnyHeader();
            }
            else
            {
                policy.WithHeaders(this.Headers);
            }

            if (this.AllowAnyMethod)
            {
                policy.AllowAnyMethod();
            }
            else
            {
                policy.WithMethods(this.Methods);
            }

            if (this.SupportsCredentials)
            {
                policy.AllowCredentials();
            }
            else
            {
                policy.DisallowCredentials();
            }

            return(policy.Build());
        }
Beispiel #27
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSignalR()
            .AddHubOptions <UpdateStatusHub>((hub) =>
            {
                hub.EnableDetailedErrors = true;
            });

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <WebPagesContext>(options =>
            {
                options.UseNpgsql(ConnectionString);
            });

            services.AddAuthorization(x =>
            {
                x.DefaultPolicy = new AuthorizationPolicyBuilder()
                                  .RequireAssertion((ctx) => {
                    var httpContext = ((ActionContext)ctx.Resource).HttpContext;
                    var headers     = httpContext.Request.Headers as FrameRequestHeaders;
                    return(headers == null || headers.HeaderAuthorization.Any());
                })
                                  .Build();
            });

            services.AddScoped <IRepository <WebPage>, WebPages>();
            services.AddSingleton <WebPagesMonitor>();
        }
Beispiel #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // DbContext:
            services.AddDbContext <DataModel.Models.EF.TranslationContext>(options =>
                                                                           options
                                                                           .UseNpgsql(Configuration.GetConnectionString("TranslationsDatabase"))
                                                                           .UseSnakeCaseNamingConvention());

            // AutoMapper:
            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddExpressionMapping();
                mc.AddProfile(new AutoMapperProfile());
            });

            services.AddSingleton(mapperConfig.CreateMapper());

            // TranslationOps
            services.AddScoped <ITranslationOps, TranslationOps>();
            services.AddScoped <ITranslationService, GoogleTranslationService>();
            services.AddScoped <ILanguageService, GoogleLanguageService>((x) => new GoogleLanguageService(Configuration));

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "TranslationStation", Version = "v1"
                });
            });
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            //corsBuilder.AllowAnyOrigin(); // For anyone access.
            corsBuilder.WithOrigins("http://localhost:8080"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Beispiel #29
0
        private void BuildPolicies()
        {
            string content;

            using (var streamReader = new StreamReader(_fileProvider.GetFileInfo(_options.SettingsFileName).CreateReadStream()))
            {
                content = streamReader.ReadToEnd();
            }
            var policySettings = JsonConvert.DeserializeObject <IEnumerable <PolicySetting> >(content);

            var temp = new Dictionary <string, CorsPolicy>(StringComparer.OrdinalIgnoreCase);

            foreach (var policySetting in policySettings)
            {
                var corsPolicyBuilder = new CorsPolicyBuilder();
                if (policySetting.AllowedOrigins == null || policySetting.AllowedOrigins.Length == 0)
                {
                    corsPolicyBuilder.AllowAnyOrigin();
                }
                else
                {
                    corsPolicyBuilder.WithOrigins(policySetting.AllowedOrigins);
                }

                if (policySetting.AllowedHeaders == null || policySetting.AllowedHeaders.Length == 0)
                {
                    corsPolicyBuilder.AllowAnyHeader();
                }
                else
                {
                    corsPolicyBuilder.WithHeaders(policySetting.AllowedHeaders);
                }

                temp.Add(policySetting.Name, corsPolicyBuilder.Build());
            }

            // Delay 'updating' the policies as late as possible to prevent corrupting ongoing requests from
            // reading bad policy settings
            _policies = temp;

            _logger.LogInformation("Updated CORS policies");
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <EmailServerContext>(o => o.UseInMemoryDatabase("Email"));

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc();

            services.AddTransient <EmailComponent, EmailComponent>();
        }
Beispiel #31
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Collection of services</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add CORS
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", corsBuilder.Build());
            });

            // Expose the Configuration
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add custom services
            Cloud.RunningCloud.AddServices(services);
        }
Beispiel #32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <UbcDbContext>(opt => opt.UseNpgsql(Configuration.GetConnectionString("UbcDatabase")));
            services.AddMvc();

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Beispiel #33
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

            services.AddIdentity<ApplicationUser, IdentityRole>(configuration =>
            {
                //ToDo: Refaktorovat. Extrahovat do zvlast triedy, ked bude jasne ako ideme riesit autorizaciu.
                configuration.Password.RequiredLength = 8;
                configuration.Password.RequireLowercase = false;
                configuration.Password.RequireUppercase = false;
                configuration.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") &&
                            ctx.Response.StatusCode == (int)HttpStatusCode.OK)
                        {
                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }

                        return Task.FromResult(0);
                    }
                };
            })

            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc();

            services.AddOptions();
            services.Configure<EmailOptions>(Configuration.GetSection("Email"));

            //toto som pridal
             /*   services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
            });
            */

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options => {
                options.AddPolicy("AllowAll", corsBuilder.Build());
                });

            // Add application services
            AddIntraWebServices(services);

            //services.AddInstance<IRoomRepository>(new Models.Dummies.RoomDummyRepository()); //Testovacia implementacia
            InitializeAutoMapper(services);
        }
Beispiel #34
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //Add CORS support.
            // Must be first to avoid OPTIONS issues when calling from Angular/Browser
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("allReady", corsBuilder.Build());
            });

            // Add Application Insights data collection services to the services container.
            services.AddApplicationInsightsTelemetry(Configuration);

            // Add Entity Framework services to the services container.
            services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage"));
            services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection"));
            services.Configure<EmailSettings>(Configuration.GetSection("Email"));
            services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData"));
            services.Configure<GeneralSettings>(Configuration.GetSection("General"));
            services.Configure<GetASmokeAlarmApiSettings>(Configuration.GetSection("GetASmokeAlarmApiSettings"));
            services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter"));
            services.Configure<MappingSettings>(Configuration.GetSection("Mapping"));

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 10;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = true;
                options.Password.RequireUppercase = false;
                options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
            })
            .AddEntityFrameworkStores<AllReadyContext>()
            .AddDefaultTokenProviders();

            // Add Authorization rules for the app
            services.AddAuthorization(options =>
            {
                options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin"));
                options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin"));
            });

            services.AddLocalization();

            //Currently AllReady only supports en-US culture. This forces datetime and number formats to the en-US culture regardless of local culture
            var usCulture = new CultureInfo("en-US");
            var supportedCultures = new[] { usCulture };
            services.Configure<RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new RequestCulture(usCulture, usCulture);
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });

            // Add MVC services to the services container.
            // config add to get passed Angular failing on Options request when logging in.
            services.AddMvc(config =>
            {
                config.ModelBinderProviders.Insert(0, new AdjustToTimezoneModelBinderProvider());
            })
                .AddJsonOptions(options =>
                options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            //Hangfire
            services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"]));

            // configure IoC support
            var container = CreateIoCContainer(services);
            return container.Resolve<IServiceProvider>();
        }