示例#1
0
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowCredentials();
            corsBuilder.WithOrigins(_secret.CorsAllowedOrigins);
            //corsBuilder.AllowAnyOrigin();

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

            services.AddAuthorization();

            // Add framework services.
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            string appRoot  = Environment.CurrentDirectory;
            string database = System.IO.Path.Combine(appRoot + @"\", @"App_Data\flixgo.db");

            services.AddDbContext <FlixGoContext> (options => options.UseSqlite("Data Source=" + database));
            services.AddScoped <IFlixGoRepository, FlixGoRepository>();

            //Transient objects are always different; a new instance is provided to every controller and every service.
            //Scoped objects are the same within a request, but different across different requests.
            //Singleton objects are the same for every object and every request.
        }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSingleton(async mantleConfig =>
            {
                var config = new Configuration
                {
                    BasePath = "https://api.mantle.services"
                };
                var auth         = new AuthenticationApi(config);
                var userResponse = await auth.AuthenticationLoginPostAsync(new UserLoginRequest("mantleEmail", "mantlePass"));
                config.AddDefaultHeader("Authorization", userResponse.AccessToken);
                return(config);
            });

            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddRequestScopingMiddleware(() => scopeProvider.Value = new Scope());
            services.AddCustomControllerActivation(Resolve);
            services.AddCustomViewComponentActivation(Resolve);
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Empower API", Version = "v1"
                });
            });
            services.AddMvc();

            var corsBuilder = new CorsPolicyBuilder();

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

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

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("SiteCorsPolicy"));
            });
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext <AccountsContext>(ConfigureDatabase);


            //CORS
            var corsBuilder = new CorsPolicyBuilder();

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

            //REPOSITORIOS
            services.AddScoped <IAccountRepository, AccountRepository>();
            services.AddScoped <IPersonRepository, PersonRepository>();
            services.AddScoped <ITransactionRepository, TransactionRepository>();

            //SERVICOS
            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <IPersonService, PersonService>();
            services.AddScoped <ITransactionService, TransactionService>();

            services.AddLogging();
        }
示例#5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <DBContext>();

            // CORS
            //Cors 셋팅
            services.AddCors(options =>
            {
                var origins = Configuration.GetSection("AllowedOrigins").GetChildren().Select(a => a.Value).ToArray();
                var builder = new CorsPolicyBuilder(origins);
                builder.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
                options.AddDefaultPolicy(builder.Build());
            });

            // Router
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                options.SerializerSettings.DateParseHandling    = DateParseHandling.DateTimeOffset;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
示例#6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationContext>(options =>
                                                       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Soccer matches", Version = "v1"
                });
            });

            services.AddCors();

            // ********************
            // 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());
            });

            services.AddMvc();
        }
示例#7
0
        public CorsPolicy Build()
        {
            CorsPolicyBuilder policy = new CorsPolicyBuilder();

            ApplyAlls();

            var origins = Origins.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

            if (origins.Any())
            {
                if (origins.First() == "*")
                {
                    policy.AllowAnyOrigin();
                }
                else
                {
                    policy.WithOrigins(origins);
                }
                if (AllowCredentials && origins.First() != "*")
                {
                    policy.AllowCredentials();
                }
                else
                {
                    policy.DisallowCredentials();
                }
            }

            var methods = Methods.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

            if (methods.Any())
            {
                if (methods.First() == "*")
                {
                    policy.AllowAnyMethod();
                }
                else
                {
                    policy.WithMethods(methods);
                }
            }

            var headers = Headers.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

            if (headers.Any())
            {
                if (headers.First() == "*")
                {
                    policy.AllowAnyHeader();
                }
                else
                {
                    policy.WithHeaders(headers);
                }
            }

            policy.SetIsOriginAllowedToAllowWildcardSubdomains();

            return(policy.Build());
        }
示例#8
0
        public void ConfigureServices(IServiceCollection services)
        {
            #region Setup CORS

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithOrigins("http://192.168.1.109:4200", "http://46.98.190.16:4200",
                                    "http://192.168.88.33:4200", "http://46.98.128.9:4200",
                                    "http://localhost:4200", "http://localhost:44362", "http://localhost:44342"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowCredentials();
            corsBuilder.AllowAnyMethod();

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

            #endregion

            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors  = true;
                hubOptions.KeepAliveInterval     = TimeSpan.FromSeconds(10);
                hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(110);
                hubOptions.HandshakeTimeout      = TimeSpan.FromSeconds(30);
            });

            DependencyConfiguration.Configure();
        }
示例#9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddEntityFrameworkNpgsql().AddDbContext <DBContext>(options => options.UseNpgsql(connectionString));

            IdentityBuilder builder = services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = true;
            }
                                                                              );

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddSignInManager <SignInManager <IdentityUser> >();
            builder.AddEntityFrameworkStores <DBContext>();
            builder.AddDefaultTokenProviders();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme      = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["JwtIssuer"],
                    ValidAudience    = Configuration["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                    ClockSkew        = TimeSpan.Zero
                };
            });

            var corsBuilder = new CorsPolicyBuilder();

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


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

            services.AddMvc();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
示例#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();
            var corsBuilder = new CorsPolicyBuilder();

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

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

            // Add framework services.
            services.AddMvc();
            services.AddMvcCore();
            //var connectionString = "User ID=postgres;Password=uiop789;Host=localhost;Port=5432;Database=eaidev;Pooling=true";
            //var connectionString = "User ID=postgres;Password=postgres@2017;Host=10.152.10.65;Port=5432;Database=eaidev;Pooling=true";

            var connectionString = Configuration.GetSection("PostgesConnection:connectionString").Value;

            services.Configure <Settings>(options =>
            {
                options.ConnectionString = Configuration.GetSection("PostgesConnection:connectionString").Value;
            });

            services.AddDbContext <EAIContext>(
                opts => opts.UseNpgsql(connectionString)
                );
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MapperProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddMvc(config =>
            {
                config.Filters.Add(new ATMExceptionFilter());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDbContextPool <ATMBankContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ATMConnection"),
                                                                                       o => o.EnableRetryOnFailure())
                                                       .UseLazyLoadingProxies()
                                                       .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.
                                                                                                     QueryClientEvaluationWarning)));
            services.AddScoped <ICardRepository, CardRepository>();
            services.AddScoped <ICardService, CardService>();
            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#12
0
        // 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:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

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

            var defaultCon = Configuration.GetConnectionString("Default");

            services.AddDbContext <PapaJohnsCloneDbContext>(options => options.UseSqlServer(defaultCon));

            var analyticsCon = Configuration.GetConnectionString("AnalyticsConString");

            services.AddDbContext <AnalyticsDbContext>(options => options.UseSqlServer(analyticsCon));
        }
示例#13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("SampleData");

            services.AddDbContext <Mcontext>(cfg => cfg.UseSqlServer(connectionString));

            // ********************
            // Setup CORS

            var corsBuilder = new CorsPolicyBuilder();

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

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

            services.AddMvc();
        }
示例#14
0
文件: Startup.cs 项目: kinmat/Temalab
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var corsBuilder = new CorsPolicyBuilder();

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



            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });


            services.AddDbContext <TaskContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("TaskContext")));
        }
示例#15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <AuthRepository>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var signingKey = Convert.FromBase64String(Configuration["Jwt:SigningSecret"]);
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(signingKey)
                };
            });

            CorsPolicyBuilder corsBuilder = new CorsPolicyBuilder();

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

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


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            RegisterServices(services);
            SetAuthCookieServices(services);
        }
示例#16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext <DataKelasContext>(options =>
                                                     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddCookie()
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateActor            = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew                = TimeSpan.Zero,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer              = Configuration["Token:Issuer"],
                    ValidAudience            = Configuration["Token:Audience"],
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Token:Key"]))
                };
            });
            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());
            });
        }
示例#17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

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

            services.AddTransient <IValidator <CustomerDto>, CustomerDtoValidator>();
            services.AddTransient <IValidator <AddressDto>, AddressDtoValidator>();

            services.AddDbContext <CustomersListContext>
                (options => options.UseSqlServer(Configuration.GetConnectionString("CustomersDatabase")));

            services.AddScoped <ICustomerService, CustomerService>();

            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#18
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);
            }
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AddressBookDatabaseSettings>(Configuration.GetSection(nameof(AddressBookDatabaseSettings)));

            services.AddSingleton <IAddressBookDatabaseSettings>(sp => sp.GetRequiredService <IOptions <AddressBookDatabaseSettings> >().Value);

            services.AddSingleton <UserService>();
            services.AddSingleton <ContactService>();

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

            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#20
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();

            var corsBuilder = new CorsPolicyBuilder();

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

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

            var ldapConnection = new LDAPConnectionInfo()
            {
                Host = Configuration["AppSettings:LDAP:Host"],
                Port = int.Parse(Configuration["AppSettings:LDAP:Port"])
            };

            services.AddSingleton(ldapConnection);

            //for testing
            services.AddScoped <IAuthenticationProvider, StaticUsersAuthProvider>();
            //services.AddScoped<IAuthenticationProvider, LDAPAuthenticationProvider>();
        }
示例#21
0
 /// <summary>
 /// 跨域策略 选项
 /// </summary>
 /// <param name="option"></param>
 internal static void CorsConfigBuild(CorsPolicyBuilder option)
 {
     option.AllowAnyHeader();
     option.AllowAnyMethod();
     option.AllowAnyOrigin();
     //cfg.AllowCredentials();
 }
示例#22
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.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("AllowMyOrigin", corsBuilder.Build());
            });

            /*
             * services.AddCors(options =>
             * {
             *  options.AddPolicy("AllowMyOrigin",
             *  builder => builder
             *      .WithOrigins("http://localhost:3000")
             *      .AllowAnyMethod()
             *      .AllowAnyHeader());
             * });
             */

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
示例#23
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.AddApplicationInsightsTelemetry(Configuration);

            services.AddRouting(x =>
            {
                x.LowercaseUrls = true;
            });
            services.AddMvc();

            services.AddApiVersioning(o =>
            {
                //                o.AssumeDefaultVersionWhenUnspecified = true;
                //                o.DefaultApiVersion = new ApiVersion(new DateTime(2016, 7, 1));
            });

            // cors
            var corsBuilder = new CorsPolicyBuilder();

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

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

            services.AddSwaggerGen();

            services.AddDbContext <JunSpaContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
示例#24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Pega string de conexão banco de dados
            var connection = Configuration["ConexaoMySql:MySqlConnectionString"];

            // Serviço que se conecta com o banco de dados
            services.AddDbContext <SeguroDbContext>(options =>
                                                    options.UseMySQL(connection)
                                                    );
            //serviço que registra a dependncia utilizada
            services.AddTransient <IApoliceNegocio, ApoliceNegocio>();
            //Serviço que habilita o MVC
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // ********************
            // Setup CORS
            // ********************
            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());
            });
        }
示例#25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var inMemoryDbEnabled = Configuration.GetValue <bool>("InMemoryDbEnabled");

            if (inMemoryDbEnabled)
            {
                services.AddDbContext <BookLibraryDbContext>(options =>
                                                             options.UseInMemoryDatabase("BookLibrary"));
            }
            else
            {
                services.AddDbContext <BookLibraryDbContext>(options =>
                                                             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }

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

            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "eBooks", Version = "v1"
                });
            });

            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("AllowOrigin", corsBuilder.Build());
            });
        }
示例#27
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();

            var corsBuilder = new CorsPolicyBuilder();

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

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

            //Add the dependancy injection...
            services.AddSingleton <Interfaces.ITodoRepository, Repositories.TodoRepository>();
            services.AddTransient <Interfaces.IOperationTransient, Operation>();
            services.AddScoped <Interfaces.IOperationScoped, Operation>();
            services.AddSingleton <Interfaces.IOperationSingleton, Operation>();
            services.AddSingleton <Interfaces.IOperationSingletonInstance>(new Operation(Guid.Empty));
            services.AddTransient <OperationService, OperationService>();
        }
示例#28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin();
                });
            });

            services.AddMvc();

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

            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#29
0
        private static void InitCorsOptions(IConfiguration configuration, CorsPolicyBuilder policyBuilder)
        {
            string origins = configuration.GetValue <string>("Cors:origins");
            string methods = configuration.GetValue <string>("Cors:methods");
            string headers = configuration.GetValue <string>("Cors:headers");

            if (origins == CorsConstants.AnyOrigin)
            {
                policyBuilder.AllowAnyOrigin();
            }
            else
            {
                policyBuilder.WithOrigins(origins.Split(','));
            }
            if (methods == "*")
            {
                policyBuilder.AllowAnyMethod();
            }
            else
            {
                policyBuilder.WithMethods(methods.Split(','));
            }
            if (headers == "*")
            {
                policyBuilder.AllowAnyHeader();
            }
            else
            {
                policyBuilder.WithHeaders(headers.Split(','));
            }
        }
示例#30
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("default");

            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(connectionString));

            // Add services
            // When I ask for IUserService give me UserService
            services.AddTransient <IUserService, UserService>();

            // Singleton: 1 for Application Lifecycle
            // Scoped: 1 for 1 Http Request
            // Transient: Give me a fresh one everytime

            services.AddMvc();

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

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("wildcard", corsBuilder.Build());
            });
        }
示例#31
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>();
        }
示例#32
0
        public void AllowAnyMethod_AllowsAny()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.AllowAnyMethod();

            // Assert
            var corsPolicy = builder.Build();
            Assert.True(corsPolicy.AllowAnyMethod);
            Assert.Equal(new List<string>() { "*" }, corsPolicy.Methods);
        }
示例#33
0
文件: Startup.cs 项目: HTBox/allReady
        // 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>();
        }
示例#34
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);
        }