// 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 AllowCredential_SetsSupportsCredentials_ToTrue() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.AllowCredentials(); // Assert var corsPolicy = builder.Build(); Assert.True(corsPolicy.SupportsCredentials); }
public void AllowAnyOrigin_AllowsAny() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.AllowAnyOrigin(); // Assert var corsPolicy = builder.Build(); Assert.True(corsPolicy.AllowAnyOrigin); Assert.Equal(new List<string>() { "*" }, corsPolicy.Origins); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <PeladeirosContext>(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); services.AddCors(options => { options.AddPolicy("PoliticaDeAcesso", corsBuilder.Build()); }); services.AddControllers(); }
// 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 virtual void ConfigureServices(IServiceCollection services) { // Add CORS policy var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); // Add MVC services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>)); // Add MediatR services.AddMediatR(typeof(GetCatsQuery).GetTypeInfo().Assembly); // Add AppSettings services.Configure <AppSettings>(Configuration); // Add Services services.AddTransient <IApiResponseHandler, ApiResponseHandler>(); services.AddTransient <IErrorResponseFactory, ErrorResponseFactory>(); // Add HTTP Services services.AddHttpClient(); services.AddHttpClient <IPeopleService, PeopleService>(); // Add Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = API_NAME, Version = "V1" }); c.EnableAnnotations(); c.DescribeAllEnumsAsStrings(); c.CustomSchemaIds(x => x.FullName); }); }
// 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(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); // Add framework services. services.AddMvc(); }
// 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:4200"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); // Add configuration for Swagger services.AddSwaggerCommon(); services.AddMvc(); }
// 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("SiteCorsPolicy", corsBuilder.Build()); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public void Constructor_WithNoOrigin() { // Arrange & Act var builder = new CorsPolicyBuilder(); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyHeader); Assert.False(corsPolicy.AllowAnyMethod); Assert.False(corsPolicy.AllowAnyOrigin); Assert.False(corsPolicy.SupportsCredentials); Assert.Empty(corsPolicy.ExposedHeaders); Assert.Empty(corsPolicy.Headers); Assert.Empty(corsPolicy.Methods); Assert.Empty(corsPolicy.Origins); Assert.Null(corsPolicy.PreflightMaxAge); }
// 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(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPol", corsBuilder.Build()); } ); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
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); }
public void WithHeaders_AddsHeaders() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithHeaders("example1", "example2"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyHeader); Assert.Equal(new List <string>() { "example1", "example2" }, corsPolicy.Headers); }
public void WithMethods_AddsMethods() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithMethods("PUT", "GET"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List <string>() { "PUT", "GET" }, corsPolicy.Methods); }
public void WithOrigins_AddsOrigins() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithOrigins("http://example.com", "http://example2.com"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List <string>() { "http://example.com", "http://example2.com" }, corsPolicy.Origins); }
// 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(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); // Add framework services. services.AddDbContext <ApplicationContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:HotelApplicationDB"])); services.AddScoped(typeof(IDataBooking <Booking, long>), typeof(BookingManager)); services.AddScoped(typeof(IDataRepository <Customer, long>), typeof(CustomerManager)); services.AddScoped(typeof(IDataAmenities <Amenities, long>), typeof(AmenitiesManager)); services.AddScoped(typeof(IDataPayment <Payment, long>), typeof(PaymentManager)); services.AddScoped(typeof(IDataReview <ReviewManager, long>), typeof(ReviewManager)); services.AddScoped(typeof(IDataRoom <Room, long>), typeof(RoomManager)); services.AddScoped(typeof(IDataRoomType <RoomType, long>), typeof(RoomTypeManager)); services.AddScoped(typeof(IDataPromo <Promo, long>), typeof(PromoManager)); services.AddScoped(typeof(IDataTraveller <Traveller, long>), typeof(TravellerManager)); services.AddScoped(typeof(IDataOption <Option, long>), typeof(OptionsManager)); services.AddMvc(); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("SiteCorsPolicy")); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <IAlbumsService, AlbumsService>(); services.AddHttpClient <IAlbumsApiClient, AlbumsApiClient>(client => { client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com"); client.Timeout = TimeSpan.FromMinutes(1); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); }); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfiles()); }); // Set Adapter pattern var mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddSwaggerGen(s => { s.SwaggerDoc("v1", new OpenApiInfo { Title = "Runpath API", Description = "Runpath API" }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 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) { // ******************** // Setup CORS // ******************** var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.WithOrigins("https://localhost:4430"); //corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); // Add framework services. //services.AddDbContext<ShoppingCartContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddEntityFrameworkSqlite() .AddDbContext <ShoppingCartContext>(option => { option.UseSqlite((Configuration["Data:DefaultConnection:ConnectionString"])); }); services.AddMvc().AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); services.AddSingleton <IProductRepository, ProductRepository>(); services.AddSingleton <ITokenProvider>(new JwtTokenProvider(GetTokenOptions())); services.AddSingleton <IShoppingCartRepository, ShoppingCartRepository>(); services.AddSingleton <IUserRepository, UserRepository>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }
// 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_1); // services.AddMvc().AddJsonOptions( options => options.SerializerSettings.ReferenceLoopHandling= Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddDbContext <DbContextApp>(options => options.UseSqlServer(Configuration.GetConnectionString("Conexion"))); //services.AddCors(options => { // options.AddPolicy("Todos", // builder => builder.WithOrigins("*").WithHeaders("*").WithMethods("*")); //}); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); services.AddMvc(); // ******************** // 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()); }); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { CorsPolicyBuilder corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); ConnectionStrings connectionStrings = new ConnectionStrings(); Configuration.GetSection("ConnectionStrings").Bind(connectionStrings); services.AddDbContext <AccountManagementDatabase>(options => options.UseSqlServer(Configuration.GetConnectionString("PrimaryDatabaseConnectionString"))); // // Built-In Dependency Injection // services.AddTransient <IAccountManagementDataService, AccountManagementDataService>(); services.AddTransient <IAccountManagementBusinessService>(provider => new AccountManagementBusinessService(provider.GetRequiredService <IAccountManagementDataService>(), connectionStrings)); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://codeproject.microservices.com", ValidAudience = "https://codeproject.microservices.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("CodeProject.Shared.Common.TokenManagement")) }; }); services.AddScoped <SecurityFilter>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
// 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.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() .AllowCredentials(); services.AddCors(options => { options.AddPolicy("MyCorsPolicy", corsBuilder.Build()); }); services.AddMvc(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("MyCorsPolicy")); }); services .AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://216.69.181.183/IdentityServer/"; options.RequireHttpsMetadata = false; options.ApiName = "api1"; options.NameClaimType = "user_name"; options.RoleClaimType = "role"; //options.typ //options. }); services .AddMvcCore(options => { // require scope1 or scope2 var policy = ScopePolicy.Create("openid", "profile"); options.Filters.Add(new AuthorizeFilter(policy)); }) .AddAuthorization() .AddJsonFormatters(); _MigrateDataBase(); }
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddScoped <IConnectionBloodOrange, UnitOfWorkBloodOrange>(x => new UnitOfWorkBloodOrange(Configuration.GetSection("Configuracoes").GetSection("Connection-BloodOrange").Value)); services.AddScoped <IMessaging, Messages>(x => new Messages(Configuration.GetSection("Messages").Value)); services.Configure <ApplicationConfiguration>(Configuration.GetSection("Aplicacao")); services.AddTransient <PerformaceFilters>(); services.AddTransient <SecurityFilter>(); AuthConfiguration.Register(services, Configuration); AutoMapperConfiguration.Register(services, Configuration); DependencyInjectionConfiguration.Register(services, Configuration); services.AddMvc(options => { options.Filters.AddService <PerformaceFilters>(); options.Filters.AddService <SecurityFilter>(); options.Filters.Add(typeof(ErrorFilters)); }).AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }).SetCompatibilityVersion(CompatibilityVersion.Latest); SwaggerApiVersioningConfiguration.Register(services); var corsBuilder = new CorsPolicyBuilder() .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin(); 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 <AisysDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped <IUserService, UserService>(); services.AddScoped <IEmployeeService, EmployeeService>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); });; // ******************** // 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.WithOrigins("http://localhost:8775"); 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 = "Aisys API", Version = "v1" }); }); ConfigureAuth(services); }
// 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("AllowAnyOrigin", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin")); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices() .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // ******************** // 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()); }); services.AddDbContext <TesteFabioCostaContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddTransient(typeof(IRepositoryBase <>), typeof(RepositoryBase <>)); services.AddScoped <IUsuariosService, UsuariosService>(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { CoreContext.ConnnectString = Configuration.GetConnectionString("CoreConnectString"); services.AddDbContext <CoreContext>(options => options.UseMySql(CoreContext.ConnnectString)); services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); #region api文档配置 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "sk.core API", Version = "v1" }); c.CustomSchemaIds((type) => type.FullName); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "sk.core.xml"); c.IncludeXmlComments(xmlPath); c.OperationFilter <AuthTokenHeaderParameter>(); //添加自定义头 }); #endregion #region 跨域配置 var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. corsBuilder.AllowCredentials(); //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); #endregion services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); //扩展服务 services.AddServiceExtensions(); }
public static CorsPolicy GetCORSPolicy() { var corsPolicyBuilder = new CorsPolicyBuilder(); corsPolicyBuilder.AllowAnyMethod(); corsPolicyBuilder.AllowAnyHeader(); corsPolicyBuilder.AllowCredentials(); if (Settings.CORSDomains != null && Settings.CORSDomains.Length > 0) { corsPolicyBuilder.WithOrigins(Settings.CORSDomains); } else { corsPolicyBuilder.AllowAnyOrigin(); } return(corsPolicyBuilder.Build()); }
private static void PerformCorsSetup(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()); }); }
// 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.AddDbContext <BaseContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddTransient <IUnitOfWork <Restaurante>, RestauranteRepository>(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); }
public static void SetAllowAll(IServiceCollection services) { var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy(ALLOW_ALL, corsBuilder.Build()); }); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory(ALLOW_ALL)); }); }
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. 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()); }
// 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_1); var connection = @"Server=(localdb)\mssqllocaldb;Database=WhatapupDb;Trusted_Connection=True;ConnectRetryCount=0"; services.AddDbContext <WhatapupDbContext>(options => options.UseSqlServer(connection)); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.WithOrigins("http://localhost:3000"); services.AddCors(options => { options.AddPolicy("RestApiPolicy", corsBuilder.Build()); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new NetTopologySuite.IO.Converters.GeoJsonConverterFactory()); }); services.AddTransient <IBakery, BakeryService>(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); services.AddCors(options => { options.AddPolicy(name: "MyPolicy", corsBuilder.Build()); }); }
// 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()); }); }
public void Constructor_WithParamsOrigin_InitializesOrigin(string origin) { // Arrange var origins = origin.Split(','); // Act var builder = new CorsPolicyBuilder(origins); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyHeader); Assert.False(corsPolicy.AllowAnyMethod); Assert.False(corsPolicy.AllowAnyOrigin); Assert.False(corsPolicy.SupportsCredentials); Assert.Empty(corsPolicy.ExposedHeaders); Assert.Empty(corsPolicy.Headers); Assert.Empty(corsPolicy.Methods); Assert.Equal(origins.ToList(), corsPolicy.Origins); Assert.Null(corsPolicy.PreflightMaxAge); }
/// <summary> /// Adds a new policy. /// </summary> /// <param name="name">The name of the policy.</param> /// <param name="configurePolicy">A delegate which can use a policy builder to build a policy.</param> public void AddPolicy(string name, Action<CorsPolicyBuilder> configurePolicy) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (configurePolicy == null) { throw new ArgumentNullException(nameof(configurePolicy)); } var policyBuilder = new CorsPolicyBuilder(); configurePolicy(policyBuilder); PolicyMap[name] = policyBuilder.Build(); }
public void WithOrigins_AddsOrigins() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithOrigins("http://example.com", "http://example2.com"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List<string>() { "http://example.com", "http://example2.com" }, corsPolicy.Origins); }
/// <summary> /// Adds a new policy. /// </summary> /// <param name="name">The name of the policy.</param> /// <param name="configurePolicy">A delegate which can use a policy builder to build a policy.</param> public void AddPolicy([NotNull] string name, [NotNull] Action<CorsPolicyBuilder> configurePolicy) { var policyBuilder = new CorsPolicyBuilder(); configurePolicy(policyBuilder); PolicyMap[name] = policyBuilder.Build(); }
public void WithHeaders_AddsHeaders() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithHeaders("example1", "example2"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyHeader); Assert.Equal(new List<string>() { "example1", "example2" }, corsPolicy.Headers); }
public void WithMethods_AddsMethods() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithMethods("PUT", "GET"); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyOrigin); Assert.Equal(new List<string>() { "PUT", "GET" }, corsPolicy.Methods); }
public void WithExposedHeaders_AddsExposedHeaders() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithExposedHeaders("exposed1", "exposed2"); // Assert var corsPolicy = builder.Build(); Assert.Equal(new List<string>() { "exposed1", "exposed2" }, corsPolicy.ExposedHeaders); }
public void SetPreFlightMaxAge_SetsThePreFlightAge() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.SetPreflightMaxAge(TimeSpan.FromSeconds(12)); // Assert var corsPolicy = builder.Build(); Assert.Equal(TimeSpan.FromSeconds(12), corsPolicy.PreflightMaxAge); }
public void Constructor_WithPolicy_AddsTheGivenPolicy() { // Arrange var policy = new CorsPolicy(); policy.Origins.Add("http://existing.com"); policy.Headers.Add("Existing"); policy.Methods.Add("GET"); policy.ExposedHeaders.Add("ExistingExposed"); policy.SupportsCredentials = true; policy.PreflightMaxAge = TimeSpan.FromSeconds(12); // Act var builder = new CorsPolicyBuilder(policy); // Assert var corsPolicy = builder.Build(); Assert.False(corsPolicy.AllowAnyHeader); Assert.False(corsPolicy.AllowAnyMethod); Assert.False(corsPolicy.AllowAnyOrigin); Assert.True(corsPolicy.SupportsCredentials); Assert.Equal(policy.Headers, corsPolicy.Headers); Assert.Equal(policy.Methods, corsPolicy.Methods); Assert.Equal(policy.Origins, corsPolicy.Origins); Assert.Equal(policy.ExposedHeaders, corsPolicy.ExposedHeaders); Assert.Equal(TimeSpan.FromSeconds(12), corsPolicy.PreflightMaxAge); }
// 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); }
// 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>(); }