private void ConfigureWebApi(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}"
            );

            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

            app.Map("/api", api =>
            {
                var corsOptions = new CorsOptions()
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = ctx =>
                        {
                            var policy = new CorsPolicy();
                            policy.Origins.Add("http://localhost:3054");
                            policy.AllowAnyHeader = true;
                            policy.Methods.Add("GET");
                            return Task.FromResult(policy);
                        }
                    }

                };
                api.UseCors(corsOptions);
                api.UseWebApi(config);
            });
        }
Exemplo n.º 2
0
        public void Configuration(IAppBuilder app)
        {
            CorsPolicy tokenCorsPolicy = new CorsPolicy
            {
                AllowAnyOrigin = true,
                AllowAnyHeader = true,
                AllowAnyMethod = true
            };

            CorsOptions corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = request => Task.FromResult(request.Path.ToString().StartsWith("/token") ? tokenCorsPolicy : null)
                }
            };

            app.UseCors(corsOptions);

            HttpConfiguration webApiConfig = new HttpConfiguration();
            app.UseWebApi(webApiConfig);

            ConfigureAuth(app);

        }
Exemplo n.º 3
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            var container = new Container();

            ConfigureWebApi(config);
            ConfigureDependencyInjection(config, container);

            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
                AllowAnyOrigin = true
            };

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            app.UseCors(corsOptions);
            app.UseWebApi(config);
        }
Exemplo n.º 4
0
 public void Configuration(IAppBuilder app)
 {
     var cors = new CorsOptions() { CorsEngine = new CorsEngine(), PolicyProvider = new CorsPolicyProvider() };
     app.UseCors(cors);
     app.UseSerilogRequestContext();
     ConfigureAuth(app);
 }
Exemplo n.º 5
0
        //
        /// <summary>
        /// taken from http://benfoster.io/blog/aspnet-webapi-cors
        /// do a more discrete cors instead of allow-all.
        /// </summary>
        /// <param name="app">injected IAppBuilder</param>
        public void UseOwinCorsOrigins(IAppBuilder app)
        {
            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true
            };
            // Try and load allowed origins from web.config.  If none are
            // configured then allow all origins.
            const string _keyCorsAllowOrigin = "cors:allowOrigins";
            string       _origins            = NSG.Library.Helpers.Config.GetStringAppSettingConfigValue(_keyCorsAllowOrigin, "");

            if (_origins == "")
            {
                corsPolicy.AllowAnyOrigin = true;
            }
            else
            {
                foreach (var _origin in _origins.Split(','))
                {
                    corsPolicy.Origins.Add(_origin);
                }
            }
            //
            var corsOptions = new Microsoft.Owin.Cors.CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            //
            app.UseCors(corsOptions);
        }
Exemplo n.º 6
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            //WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Database.SetInitializer<DisciturContext>(null);

            GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator),
                new WindsorCompositionRoot(this.container));

            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            bool   isCorsEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["CORSEnabled"]);
            string corsOrigin    = ConfigurationManager.AppSettings["CORSOrigin"];

            if (isCorsEnabled)
            {
                Microsoft.Owin.Cors.CorsOptions corsOptions = new Microsoft.Owin.Cors.CorsOptions();
                corsOptions.PolicyProvider = new ConfigCorsPolicy(corsOrigin);
                app.UseCors(corsOptions);
            }

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = OAuthDefaults.AuthenticationType,
            //    LoginPath = new PathString("/Account/Login")
            //});
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();

            //http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
            //https://stackoverflow.com/questions/25997592/dependency-injection-using-simpleinjector-and-oauthauthorizationserverprovider/26034641#26034641
        }
Exemplo n.º 7
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = c => Task.FromResult(new CorsPolicy
                        {
                            AllowAnyHeader = true,
                            AllowAnyMethod = true,
                            AllowAnyOrigin = true,
                            SupportsCredentials = true
                        })
                }
            };

            appBuilder.UseCors(corsOptions);

            appBuilder.UseWebApi(config);
        }
Exemplo n.º 8
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            //UseRedisBackplane();
            //UseServiceBusBackplane();
            //UseSqlBackplane();

            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                CorsPolicy corsPolicy = new CorsPolicy()
                {
                    AllowAnyHeader = true,
                    //AllowAnyOrigin = true,
                    AllowAnyMethod = true,
                    SupportsCredentials = true
                };

                // Get Allowed Origins from Config and split by comma. Can be changed to any character that you chose.
                string[] origins = AppSettingsConfig.CorsPolicyOrigins.Split(',');

                // To split by multiple types use the following example as a template:
                //string[] origins = AppSettingsConfig.CorsPolicyOrigins.Split(',', '+');

                foreach (string origin in origins)
                {
                    corsPolicy.Origins.Add(origin);
                }

                var corsOptions = new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context => Task.FromResult(corsPolicy)
                    }
                };

                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(corsOptions);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    EnableDetailedErrors = true,
                    //EnableJSONP = true,
                    //EnableJavaScriptProxies = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
            //app.MapSignalR();
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseAppBuilder(appBuilder =>
            {
                appBuilder.SetDataProtectionProvider(new MachineKeyProtectionProvider());

                appBuilder.Map("/signalr", map =>
                {
                    // Setup the CORS middleware to run before SignalR.
                    // By default this will allow all origins. You can
                    // configure the set of origins and/or http verbs by
                    // providing a cors options with a different policy.

                    //http://ng2a-hneu-web-ui.azurewebsites.net
                    var corsOptions = new Microsoft.Owin.Cors.CorsOptions
                    {
                        PolicyProvider = new CorsPolicyProvider
                        {
                            PolicyResolver = context => ResolvePolicy()
                        }
                    };
                    map.UseCors(corsOptions);
                    //map.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
                    var hubConfiguration = new HubConfiguration
                    {
                        // You can enable JSONP by uncommenting line below.
                        // JSONP requests are insecure but some older browsers (and some
                        // versions of IE) require JSONP to work cross domain
                        // EnableJSONP = true
                        EnableDetailedErrors = true
                    };
                    // Run the SignalR pipeline. We're not using MapSignalR
                    // since this branch already runs under the "/signalr"
                    // path.
                    map.RunSignalR(hubConfiguration);
                });
                //var options = new CorsOptions();
                //options.AddPolicy("", new )
                //appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            });


            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseMvc();


            GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule());

            app.UseStaticFiles();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a new instance of CorsMiddleware.
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public CorsMiddleware(OwinMiddleware next, CorsOptions options)
            : base(next)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _corsPolicyProvider = options.PolicyProvider ?? new CorsPolicyProvider();
            _corsEngine         = options.CorsEngine ?? new CorsEngine();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Adds a CORS middleware to your web application pipeline to allow cross domain requests.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method</param>
        /// <param name="options">An options class that controls the middleware behavior</param>
        /// <returns>The original app parameter</returns>
        public static IAppBuilder UseCors(this IAppBuilder app, CorsOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            return app.Use(typeof(CorsMiddleware), options);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a new instance of CorsMiddleware.
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public CorsMiddleware(AppFunc next, CorsOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _next = next;
            _corsPolicyProvider = options.PolicyProvider ?? new CorsPolicyProvider();
            _corsEngine         = options.CorsEngine ?? new CorsEngine();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a new instance of CorsMiddleware.
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public CorsMiddleware(AppFunc next, CorsOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _next = next;
            _corsPolicyProvider = options.PolicyProvider ?? new CorsPolicyProvider();
            _corsEngine = options.CorsEngine ?? new CorsEngine();
        }
Exemplo n.º 14
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            var container = IocConfig.Setup();
            config.DependencyResolver = new DependencyResolver(container);
            config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger(container.GetInstance<ILoggingService>()));

            // Web API routes
            config.MapHttpAttributeRoutes();

            ConfigureOAuth(app);

            //http://benfoster.io/blog/aspnet-webapi-cors
            //To Allow CROSS-ORIGIN requests Globally at application level
            var corsPolicy = new CorsPolicy { AllowAnyMethod= true, AllowAnyHeader = true};
            var corsSettings = (NameValueCollection)ConfigurationManager.GetSection("CorsSettings");
            var allowedOrigins = corsSettings["AllowedOrigins"];
            //corsPolicy.Headers.Add("content-type");
            //corsPolicy.Headers.Add("accept");

            if (allowedOrigins != null)
            {
                foreach (var origin in allowedOrigins.Split(';'))
                {
                    corsPolicy.Origins.Add(origin);

                }
            }
            else
            {
                corsPolicy.AllowAnyOrigin = true;
            }

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            app.UseCors(corsOptions);

            app.UseWebApi(config);
        }
Exemplo n.º 15
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
             //   SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

            var policy = new CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                AllowAnyOrigin = true,
                SupportsCredentials = true,

            };
            policy.ExposedHeaders.Add("Location");

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            };
            app.UseCors(corsOptions);
            app.UseUnityContainer();

            var configuration = new HttpConfiguration();
            configuration.MapHttpAttributeRoutes();
            configuration.AddKatanaUnityDependencyResolver();

            var jsonFormatter = new JsonMediaTypeFormatter();
            var settings = jsonFormatter.SerializerSettings;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.Converters.Add(new OgrEntityConverter());
            jsonFormatter.SerializerSettings.Converters.Add(new DbGeographyGeoJsonConverter());

            configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            app.GetUnityContainer().RegisterType<IDataSource>(new HierarchicalLifetimeManager(),
                new InjectionFactory(factory));

            app.Map(new PathString("/api"), builder =>
            {
                builder.UseWebApi(configuration);
            });
        }
Exemplo n.º 16
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var tokenCorsPolicy = new CorsPolicy {
                AllowAnyOrigin = true,
                AllowAnyHeader = true,
                AllowAnyMethod = true
            };

            var corsOptions = new CorsOptions {
                PolicyProvider = new CorsPolicyProvider {
                    PolicyResolver = request => Task.FromResult(
                        request.Path.ToString().StartsWith("/auth/token") ? tokenCorsPolicy : null
                    )
                }
            };
            app.UseCors(corsOptions);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
Exemplo n.º 17
0
        public static void Register(IAppBuilder app, HttpConfiguration config)
        {
            var corsPolicy = new CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true
            };

            var applicationConfiguration =
                (config.Properties["container"] as IUnityContainer).Resolve<IApplicationConfiguration>();

            if (applicationConfiguration == null)
            {
                throw new ConfigurationErrorsException("AssetViewConfiguration was not available");
            }

            if (applicationConfiguration.CorsOrigins.Any())
            {
                foreach (var corsOrigin in applicationConfiguration.CorsOrigins)
                {
                    corsPolicy.Origins.Add(corsOrigin);
                }
            }
            else
            {
                corsPolicy.AllowAnyOrigin = true;
            }

            var corsOptions = new CorsOptions
            {
                PolicyProvider =
                    new CorsPolicyProvider {PolicyResolver = context => Task.FromResult(corsPolicy)}
            };

            app.UseCors(corsOptions);
        }
Exemplo n.º 18
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true

            };

            corsPolicy.Origins.Add("http://localhost:9017");

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            app.UseCors(corsOptions); //Microsoft.Owin.Cors.CorsOptions.AllowAll
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 19
0
        /// <summary>
        /// Configures the application to use the OAuthBearerToken middleware
        /// </summary>
        /// <param name="app">The application to mount the middleware on</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            //  app.UseCookieAuthentication(new CookieAuthenticationOptions());
              //  app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalBearer);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath = new PathString("/Login"),
                LogoutPath = new PathString("/Logout"),
            });
            app.SetDefaultSignInAsAuthenticationType("External");

            CorsOptions cors = new CorsOptions();
            app.UseCors(cors);
            // Mounts the middleware on the provided app with the options configured
            // above
            app.UseOAuthBearerTokens(OAuthOptions);
            //    app.UseMicrosoftAccountAuthentication(
            //clientId: "",
            //clientSecret: "");
            //    app.UseTwitterAuthentication(
            //        consumerKey: "",
            //        consumerSecret: "");
            //    app.UseFacebookAuthentication(
            //        appId: "",
            //        appSecret: "");
            //    app.UseGoogleAuthentication();
        }
Exemplo n.º 20
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            //WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Database.SetInitializer<DisciturContext>(null);

            GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator),
                new WindsorCompositionRoot(this.container));

            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            bool isCorsEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["CORSEnabled"]);
            string corsOrigin = ConfigurationManager.AppSettings["CORSOrigin"];
            if (isCorsEnabled)
            {
                Microsoft.Owin.Cors.CorsOptions corsOptions = new Microsoft.Owin.Cors.CorsOptions();
                corsOptions.PolicyProvider = new ConfigCorsPolicy(corsOrigin);
                app.UseCors(corsOptions);
            }

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = OAuthDefaults.AuthenticationType,
            //    LoginPath = new PathString("/Account/Login")
            //});
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();

            //http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
            //https://stackoverflow.com/questions/25997592/dependency-injection-using-simpleinjector-and-oauthauthorizationserverprovider/26034641#26034641
        }