Пример #1
0
        public void Configure(CorsPolicyBuilder options, IServiceCollection services)
        {
            var settings = new ServiceSettings().Auth;

            options.WithOrigins(settings.ValidAuthReferrers);
            options.WithHeaders("X-Requested-With", "Content-Type");
            options.WithMethods("POST");
            options.AllowCredentials();
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //database conn stuff
            //logger.LogInformation("Using SQL Server repository");
            services.AddScoped <IArtistRepository, ArtistRepository>();
            services.AddScoped <ILocationRepository, LocationRepository>();
            services.AddScoped <IQuizRepository, QuizRepository>();
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <CulturalDbContext>(options
                                              => options.UseSqlServer(Configuration["ConnectionString"]));

            services.AddSingleton <IAuthorizationHandler, HasScopeHandler>();

            string domain = $"https://{Configuration["Auth0:Domain"]}/";

            services.AddAuthentication(options =>
            {
                //AuthenticationOptions s;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = domain;
                options.Audience  = Configuration["Auth0:ApiIdentifier"];
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("read:artists", policy => policy.Requirements.Add(new HasScopeRequirement("read:artists", domain)));
                options.AddPolicy("write:artists", policy => policy.Requirements.Add(new HasScopeRequirement("write:artists", domain)));

                options.AddPolicy("read:quiz", policy => policy.Requirements.Add(new HasScopeRequirement("read:quiz", domain)));
                options.AddPolicy("write:quiz", policy => policy.Requirements.Add(new HasScopeRequirement("write:quiz", domain)));

                options.AddPolicy("read:location", policy => policy.Requirements.Add(new HasScopeRequirement("read:location", domain)));
                options.AddPolicy("write:location", policy => policy.Requirements.Add(new HasScopeRequirement("write:location", domain)));
            });

            // ********************
            // 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:5100", "http://52.89.227.233:5000");
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Пример #3
0
 void ConfigurePolicy(CorsPolicyBuilder builder)
 {
     builder
     .WithOrigins("http://localhost", "http://localhost:80", "http://localhost:8080", "http://localhost:3000", "http://localhost:3001", "https://localhost:44389")
     .AllowAnyOrigin()
     .AllowAnyMethod()
     .AllowAnyHeader()
     .AllowCredentials();
 }
Пример #4
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.AddHttpContextAccessor();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
            });


            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    NameClaimType            = "name",
                    ValidIssuer      = "http://*****:*****@345"))
                };
            });

            services.AddIdentity <Student, IdentityRole>(options =>
            {
                options.ClaimsIdentity.UserIdClaimType = JwtRegisteredClaimNames.Sub;
            });

            services.AddCors(options =>
            {
                var corsBuilder = new CorsPolicyBuilder();
                corsBuilder.AllowAnyHeader();
                corsBuilder.AllowAnyMethod();
                corsBuilder.WithOrigins(Configuration["WhiteList"]);
                corsBuilder.AllowCredentials();
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddBusinessLogic(Configuration.GetConnectionString("AcademicManagement"));
            services.AddHangfire(config =>
                                 config.UseSqlServerStorage(Configuration.GetConnectionString("AcademicManagement")));
            services.AddSignalR();
        }
Пример #5
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";
            });
        }
Пример #6
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:4200"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);
            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = "MeliRosales",
                    ValidAudience    = "MeliRosales",
                    IssuerSigningKey = JwtSecurityKey.Create(appSettings.Secret)
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " +
                                          context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " +
                                          context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        }
Пример #7
0
    public void WithOrigins_ThrowsIfArgumentArrayContainsNull()
    {
        // Arrange
        var builder = new CorsPolicyBuilder();

        string[] args = new string[] { null };

        // Act / Assert
        Assert.Throws <ArgumentNullException>(() => builder.WithOrigins(args));
    }
Пример #8
0
        private static CorsPolicyBuilder InstantiateCorsPolicyBuilder(IConfiguration configuration)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins(GetAllOrigins(configuration));
            corsBuilder.AllowCredentials();
            return(corsBuilder);
        }
Пример #9
0
        private void ConfigureCors(CorsPolicyBuilder policy)
        {
            var origins = Configuration.GetSection("Host:Server:Cors").Get <string[]>();

            policy
            .WithOrigins(origins)
            .AllowCredentials()
            .AllowAnyHeader()
            .AllowAnyMethod();
        }
Пример #10
0
        public CorsPolicy GenerateCorsPolicy()
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithOrigins("https://" + ConfigureMe.GetValue <string>("Settings:StaticSiteRoot"));
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowCredentials();
            return(corsBuilder.Build());
        }
Пример #11
0
 private void CorsPolicyBuild(
     CorsPolicyBuilder builder,
     ApplicationSettings applicationSettings)
 {
     builder
     .WithOrigins(applicationSettings
                  .AcceptedClients.ToArray())
     .WithMethods("GET")
     .AllowAnyHeader();
 }
        // 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 http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)


        {
            services.AddSingleton(_config);

            //services.AddStormpath();
            //  services.AddScoped<TokenProviderMiddleware>();

            services.AddIdentity <ProductUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail         = true;
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = true;
                config.Password.RequireNonAlphanumeric = true;

                //  config.Cookies.ApplicationCookie.LoginPath
            })
            .AddEntityFrameworkStores <ProductContext>();

            services.AddLogging();

            services.AddDbContext <ProductContext>();
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <ProductContext>();

            //services.AddCors(options => options.AddPolicy("AllowAll", x => x.AllowAnyOrigin()));
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                                  builder => builder.WithOrigins("http://localhost:3000/"));
            });


            // Define CORS Policy
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithHeaders("*");
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:3000");
            //corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            corsBuilder.WithExposedHeaders().AllowAnyHeader();
            corsBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(30));

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



            // services.AddTransient<ProductContextSeedData>();
            services.AddMvc();
        }
Пример #13
0
 internal static void AddCORS(CorsPolicyBuilder builder, Configuration configData)
 {
     if (!string.IsNullOrEmpty(configData.AllowedOrigins))
     {
         if (configData.AllowedOrigins == "*")
         {
             builder.AllowAnyOrigin();
         }
         else
         {
             var allowedOrigins = configData.AllowedOrigins.Split(",", StringSplitOptions.RemoveEmptyEntries);
             builder.WithOrigins(allowedOrigins);
         }
     }
     if (!string.IsNullOrEmpty(configData.AllowedMethods))
     {
         if (configData.AllowedMethods == "*")
         {
             builder.AllowAnyMethod();
         }
         else
         {
             var allowedMethods = configData.AllowedMethods.Split(",", StringSplitOptions.RemoveEmptyEntries);
             builder.WithMethods(allowedMethods);
         }
     }
     if (!string.IsNullOrEmpty(configData.AllowedHeaders))
     {
         if (configData.AllowedHeaders == "*")
         {
             builder.AllowAnyHeader();
         }
         else
         {
             var allowedHeaders = configData.AllowedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries);
             builder.WithHeaders(allowedHeaders);
         }
     }
     if (!string.IsNullOrEmpty(configData.AllowedExposedHeaders))
     {
         var allowedExposedHeaders = configData.AllowedExposedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries);
         if (allowedExposedHeaders.Any())
         {
             builder.WithExposedHeaders(allowedExposedHeaders);
         }
     }
     if (configData.IsAllowedCredentials && configData.AllowedOrigins != "*")
     {
         builder.AllowCredentials();
     }
     else
     {
         builder.DisallowCredentials();
     }
 }
Пример #14
0
        public CorsPolicy GenerateCorsPolicy()
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();                                        // For anyone access.
            corsBuilder.WithOrigins("https://app-datumation.azurewebsites.net"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();
            return(corsBuilder.Build());
        }
 /// <summary>
 /// Adds the specified <paramref name="origins"/> using <paramref name="policyBuilder"/> when
 /// <paramref name="allowAnyOrigin"/> equals <see langword="false"/>.
 /// In another case, allows any origin using <paramref name="policyBuilder"/>.
 /// </summary>
 /// <param name="policyBuilder"></param>
 /// <param name="allowAnyOrigin"></param>
 /// <param name="origins"></param>
 private static void SetOrigins(CorsPolicyBuilder policyBuilder, bool allowAnyOrigin, string[] origins)
 {
     if (allowAnyOrigin)
     {
         policyBuilder.AllowAnyOrigin();
     }
     else
     {
         policyBuilder.WithOrigins(origins);
     }
 }
Пример #16
0
        private CorsPolicy BuildPolicy(string[] targetOrigins, TimeSpan preflightMaxAge)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithOrigins(targetOrigins)
            .WithMethods(methods)
            .AllowAnyHeader()
            .WithExposedHeaders(exposedHeaders)
            .SetPreflightMaxAge(preflightMaxAge);

            return(corsBuilder.Build());
        }
Пример #17
0
            // Refer to this article if you require more information on CORS
            // https://docs.microsoft.com/en-us/aspnet/core/security/cors
            static void BuildCorsPolicy(CorsPolicyBuilder builder)
            {
                string[] CORS_ALLOW_ALL = new string[1] {
                    "*"
                };

                builder
                .WithOrigins(CORS_ALLOW_ALL)
                .WithMethods(CORS_ALLOW_ALL)
                .WithHeaders(CORS_ALLOW_ALL)
                .Build();
            }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // ===== Add our DbContext ========
            services.AddDbContext <ApplicationDbContext>();

            // ===== Add Identity ========
            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // ===== Add Jwt Authentication ========
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = 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 // remove delay of token when expire
                };
            });

            // ===== Add CORS ========
            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();

            // ===== Add Web Cors Policy ========
            services.AddCors(options =>
            {
                options.AddPolicy("WebCorsPolicy", corsBuilder.Build());
            });

            // Register application services.
            services.AddScoped <IRoomBookingServiceRepository, RoomBookingServiceRepository>();

            // ===== Add MVC ========
            services.AddMvc();
        }
Пример #19
0
 private void UseCors(CorsPolicyBuilder builder)
 {
     builder.AllowAnyHeader().AllowAnyMethod().AllowCredentials();
     if (_env.IsProduction()) //生产环境指定跨域域名
     {
         builder.WithOrigins(_settings.CorsOrigins);
     }
     else //其他环境允许所有跨所有域名
     {
         builder.AllowAnyOrigin();
     }
 }
Пример #20
0
        private CorsPolicy Allow(string origin)
        {
            var policyBuilder = new CorsPolicyBuilder();

            var policy = policyBuilder
                .WithOrigins(origin)
                .AllowAnyHeader()
                .AllowAnyMethod()
                .Build();

            return policy;
        }
        private CorsPolicy Allow(string origin)
        {
            var policyBuilder = new CorsPolicyBuilder();

            var policy = policyBuilder
                         .WithOrigins(origin)
                         .AllowAnyHeader()
                         .AllowAnyMethod()
                         .Build();

            return(policy);
        }
        /// <summary>Set Allowed Origins</summary>
        /// <param name="builder">Cors policy builder configuration</param>
        /// <param name="itemCorsSection">Item configuration</param>
        private void SetAllowedOrigins(CorsPolicyBuilder builder, IConfiguration itemCorsSection)
        {
            var origins = itemCorsSection.GetSection("origins").Get <string[]>();

            if (origins != null)
            {
                builder.WithOrigins(origins);
            }
            else
            {
                builder.AllowAnyOrigin();
            }
        }
 public static CorsPolicyBuilder SetupCors(CorsPolicyBuilder options)
 {
     return(options.WithOrigins("http://keycloak-demo.ngrok.io",
                                "https://keycloak-demo.ngrok.io", "http://localhost:5000",
                                "https://keycloak-demo-ui.ngrok.io", "http://keycloak-demo-ui.ngrok.io",
                                "https://keycloak-demo-api.ngrok.io", "http://keycloak-demo-api.ngrok.io",
                                "https://localhost:4321", "https://intranet-dev-usz.virtualcorp.ch").AllowAnyMethod()
            // options.AllowAnyOrigin().AllowAnyMethod()
            .AllowAnyHeader()
            // .WithHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
            //.WithExposedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
            .AllowCredentials());
 }
Пример #24
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:8080");
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("example2", corsBuilder.Build());
            });
            services.AddMvc();
        }
Пример #25
0
        /// <summary>
        /// Adds the CORS configuration.
        /// </summary>
        /// <param name="services">The services collection</param>
        private void ConfigureCORS(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

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

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Пример #26
0
        private static CorsPolicyBuilder AddCorsConfiguration(this CorsPolicyBuilder builder, CorsPolicy configuration)
        {
            builder.WithOrigins(configuration.Origins);
            if (configuration.Methods?.Length > 0)
            {
                builder.WithMethods(configuration.Methods);
            }
            if (configuration.Headers?.Length > 0)
            {
                builder.WithMethods(configuration.Headers);
            }

            return(builder);
        }
Пример #27
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.WithHeaders("*");
            corsBuilder.WithMethods("*");
            corsBuilder.WithOrigins("*");
            corsBuilder.AllowCredentials();

            services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });
            // Add framework services.
            services.AddMvc().AddJsonOptions(a => a.SerializerSettings.ContractResolver = new DefaultContractResolver());;
        }
Пример #28
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:8080");
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("Aurelia-ContactsManager", corsBuilder.Build());
            });
            services.AddMvc();
            services.AddSingleton <IContactRepository, ContactRepository>();
        }
Пример #29
0
        private void ConfigureCors(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

            if (Environment.IsDevelopment())
            {
                corsBuilder.AllowAnyHeader();
                corsBuilder.AllowAnyMethod();
                corsBuilder.WithOrigins("http://localhost:4200", "http://localhost");
                corsBuilder.AllowCredentials();
            }
            else
            {
                corsBuilder.AllowAnyHeader();
                corsBuilder.AllowAnyMethod();
                corsBuilder.WithOrigins("https://two.awdware.de", "http://three.awdware.de");
                corsBuilder.AllowCredentials();
            }

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Пример #30
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.AddMvc();

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.WithOrigins(
                "http://localhost:3000"
                ).WithMethods("GET", "POST", "HEAD");
            services.AddCors(options =>
            {
                options.AddPolicy("RestPolicyBase", corsBuilder.Build());
            });
        }
        public Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
        {
            var originHeader = context.Request.Headers["Origin"].FirstOrDefault();

            // unknown policy name or origin header not present: default behavior
            if (string.IsNullOrEmpty(policyName) ||
                string.IsNullOrEmpty(originHeader) ||
                !string.Equals(policyName, DefaultSenseNetCorsPolicyName, StringComparison.InvariantCultureIgnoreCase) ||
                string.Equals(originHeader, "null", StringComparison.InvariantCultureIgnoreCase))
            {
                return(Task.FromResult(_options.GetPolicy(policyName ?? _options.DefaultPolicyName)));
            }

            var policyBuilder = new CorsPolicyBuilder();

            // Load current CORS settings from the repository. This must not be cached here,
            // because settings may change at runtime, anytime.
            var corsSettings =
                Settings.GetValue <IEnumerable <string> >(PortalSettings.SETTINGSNAME,
                                                          PortalSettings.SETTINGS_ALLOWEDORIGINDOMAINS, null,
                                                          SnCorsConstants.DefaultAllowedDomains);

            // get a configured domain (or template) that matches the origin sent by the client
            var allowedDomain = GetAllowedDomain(originHeader, corsSettings);

            if (!string.IsNullOrEmpty(allowedDomain))
            {
                // template match: set the allowed origin
                policyBuilder.WithOrigins(originHeader);

                // any origin ('*') and credentials are mutually exclusive
                if (!string.Equals(originHeader, CorsConstants.AnyOrigin))
                {
                    policyBuilder.AllowCredentials();
                }

                var allowedMethods = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDMETHODS, null,
                                                       SnCorsConstants.AccessControlAllowMethodsDefault);
                var allowedHeaders = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDHEADERS, null,
                                                       SnCorsConstants.AccessControlAllowHeadersDefault);

                policyBuilder.WithMethods(allowedMethods);
                policyBuilder.WithHeaders(allowedHeaders);
            }

            return(Task.FromResult(policyBuilder.Build()));
        }
Пример #32
0
        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);
        }