Esempio n. 1
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config         = Container.Kernel.Get <ConfigurationService>();
            var cookieSecurity = config.Current.RequireSSL ? CookieSecureOption.Always : CookieSecureOption.Never;

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = AuthenticationTypes.Password,
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly     = true,
                CookieSecure       = cookieSecurity,
                LoginPath          = "/users/account/LogOn"
            });
            app.UseApiKeyAuthentication();
        }
Esempio n. 2
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            app.Use(async(ctx, next) =>
            {
                //Example for correlating logs, track source address
                CallContext.LogicalSetData("correlationIdentifier", ctx.Environment["owin.RequestId"]);
                CallContext.LogicalSetData("sourceInfo", $"{ctx.Request.RemoteIpAddress}:{ctx.Request.RemotePort}");
                await next();
                CallContext.FreeNamedDataSlot("correlationIdentifier");
                CallContext.FreeNamedDataSlot("sourceInfo");
            })
            .UseErrorPage()
            .UseOioIdwsAuthentication(new OioIdwsAuthenticationOptions())
            .UseOioIdwsAuthorizationService(new OioIdwsAuthorizationServiceOptions
            {
                AccessTokenIssuerPath = new PathString("/accesstoken/issue"),
                IssuerAudiences       = () => Task.FromResult(new[]
                {
                    new IssuerAudiences("d9f10c97aa647727adb64a349bb037c5c23c9a7a", "test cert")
                    .Audience(new Uri("https://wsp.oioidws-net.dk")),
                }),
            })
            .Use <MyService>();
        }
Esempio n. 3
0
        public void CreateLoggerConfiguration(IAppBuilder app)
        {
            app.SetLoggerFactory(new LoggerFactory());

            app.Use<LoggingMiddleware1>(app);
            app.Use<LoggingMiddleware2>(app);
        }
Esempio n. 4
0
        /// <summary>
        /// Configures the OWIN application.
        /// </summary>
        /// <param name="app">The OWIN application.</param>
        public void Configuration(IAppBuilder app)
        {
            var asm = Assembly.GetExecutingAssembly();

            Log.Info($"{Environment.NewLine}{Environment.NewLine}[{asm.GetCustomAttribute<AssemblyProductAttribute>().Product} {asm.GetName().Version}]{Environment.NewLine}{asm.GetCustomAttribute<AssemblyCopyrightAttribute>().Copyright}{Environment.NewLine}");
            Log.Info("Starting application.");

            // Configure OWIN to use Common.Logging.
            app.SetLoggerFactory(new SomeApp.Logging.CommonOwinLoggerFactory());

            Log.Info("Configuring Data Core connection settings.");
            // Middleware that will add Data Core connection settings to the OWIN environment for each call.
            app.UseDataCoreConnectionSettings();

            if (AppStoreMode)
            {
                Log.Info("Configuring authentication.");
                ConfigureAppStoreAuthentication(app);
            }

            Log.Info("Configuring ASP.NET MVC.");
            MvcConfig.Configure();

            Log.Info("Configuring Web API.");
            WebApiConfig.Configure(app);

            Log.Info("Configuring SignalR");
            SignalRConfig.Configure(app);
        }
Esempio n. 5
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var cookieSecurity = config.Current.RequireSSL ? CookieSecureOption.Always : CookieSecureOption.Never;

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = AuthenticationTypes.Password,
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly = true,
                CookieSecure = cookieSecurity,
                LoginPath = "/users/account/LogOn"
            });
            app.UseApiKeyAuthentication();
        }
Esempio n. 6
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            app.Use(async(ctx, next) =>
            {
                //Example for correlating logs, track source address
                CallContext.LogicalSetData("correlationIdentifier", ctx.Environment["owin.RequestId"]);
                CallContext.LogicalSetData("sourceInfo", $"{ctx.Request.RemoteIpAddress}:{ctx.Request.RemotePort}");
                await next();
                CallContext.FreeNamedDataSlot("correlationIdentifier");
                CallContext.FreeNamedDataSlot("sourceInfo");
            })
            .UseErrorPage()
            .UseOioIdwsAuthorizationService(new OioIdwsAuthorizationServiceOptions
            {
                AccessTokenIssuerPath    = new PathString("/accesstoken/issue"),
                AccessTokenRetrievalPath = new PathString("/accesstoken"),
                IssuerAudiences          = () => Task.FromResult(new []
                {
                    new IssuerAudiences("d9f10c97aa647727adb64a349bb037c5c23c9a7a", "test cert")
                    .Audience(new Uri("https://wsp.oioidws-net.dk")),
                }),
                TrustedWspCertificateThumbprints = new[] { "1F0830937C74B0567D6B05C07B6155059D9B10C7" },
            })
            .Use((ctx, next) =>
            {
                ctx.Response.Write("Well hello there. Guess you didn't hit any of the AS endpoints?");
                return(Task.FromResult(0));
            });
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            /*var l = new LoggerConfiguration()
             *  .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
             *  .WriteTo.File("c:\\temp\\webapi.log")
             *  .CreateLogger();
             *
             * l.Information("Hello");*/
            app.SetLoggerFactory(new MyLoggerFactory());

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://identity.loc/core",
                RequiredScopes = new[] { "read" },
                EnableValidationResultCache = false,

                TokenProvider = new MyTokenProvider(),
                //ValidationMode = ValidationMode.ValidationEndpoint
            });

            var resolver = UnityConfig.BuildResolver();

            app.UseWebApi(WebApiConfig.Register(resolver));
        }
Esempio n. 8
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
            builder.RegisterType <ApplicationDbContext>().AsSelf().InstancePerRequest();
            var container = builder.Build();

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.Formatters.JsonFormatter.SerializerSettings.Formatting           = Formatting.Indented;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DoubleFormatConverter());
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.MessageHandlers.Add(new PlainTextToJsonHandler());
            config.Services.Add(typeof(IExceptionLogger), new SerilogExceptionLogger());
            app.SetLoggerFactory(new LoggerFactory());
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
        }
Esempio n. 9
0
        public void CreateLoggerConfiguration(IAppBuilder app)
        {
            app.SetLoggerFactory(new LoggerFactory());

            app.Use <LoggingMiddleware1>(app);
            app.Use <LoggingMiddleware2>(app);
        }
Esempio n. 10
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get <ConfigurationService>();
            var auth   = Container.Kernel.Get <AuthenticationService>();

            // Setup telemetry
            var instrumentationKey = config.Current.AppInsightsInstrumentationKey;

            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
            }

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuther;

            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            {
                // Configure cookie auth now
                localUserAuther.Startup(config, app);
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName         = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan     = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                                   .Authenticators
                                   .Where(p => !String.Equals(
                                              p.Key,
                                              Authenticator.GetName(typeof(LocalUserAuthenticator)),
                                              StringComparison.OrdinalIgnoreCase))
                                   .Select(p => p.Value);

            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Uses LogJam <see cref="Tracer" /> logging for all OWIN logging.
        /// </summary>
        /// <param name="appBuilder"></param>
        /// <returns></returns>
        public static IAppBuilder UseOwinTracerLogging(this IAppBuilder appBuilder)
        {
            Contract.Requires <ArgumentNullException>(appBuilder != null);

            appBuilder.SetLoggerFactory(new OwinLoggerFactory(appBuilder.GetTracerFactory()));

            return(appBuilder);
        }
Esempio n. 12
0
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888

            app.SetLoggerFactory(new ApiLoggerFactory());
            ServiceLog.Logger = ServiceLog.CreateLogger();
            Log.Logger        = ServiceLog.Logger;
        }
        public static void UseIdentityManager(this IAppBuilder app, IdentityManagerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("config");
            }

            app.SetLoggerFactory(new LibLogLoggerFactory());

            Logger.Info("Starting IdentityManager configuration");

            options.Validate();

            app.Use(async(ctx, next) =>
            {
                if (!ctx.Request.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) &&
                    options.SecurityConfiguration.RequireSsl)
                {
                    ctx.Response.Write("HTTPS required");
                }
                else
                {
                    await next();
                }
            });

            var container = AutofacConfig.Configure(options);

            app.Use <AutofacContainerMiddleware>(container);

            options.SecurityConfiguration.Configure(app);

            if (!options.DisableUserInterface)
            {
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets")
                });
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets/libs/fonts"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets.Content.fonts")
                });
                app.UseStageMarker(PipelineStage.MapHandler);
            }

            SignatureConversions.AddConversions(app);
            app.UseWebApi(WebApiConfig.Configure(options));
            app.UseStageMarker(PipelineStage.MapHandler);

            // clears out the OWIN logger factory so we don't recieve other hosting related logs
            app.Properties["server.LoggerFactory"] = null;
        }
Esempio n. 14
0
        private void ConfigurePipeline(IAppBuilder appBuilder)
        {
            // logging
            appBuilder.SetLoggerFactory(new ConsoleLoggerFactory());
            appBuilder.UseLogging();

            // use Web API
            appBuilder.UseWebApi(this.httpConfiguration);
        }
Esempio n. 15
0
        public void Configuration(IAppBuilder app)
        {
            // Add custom trace logging to OWIN pipeline
            app.SetLoggerFactory(new TraceLoggerFactory());

            app.UseCors(CorsOptions.AllowAll);

            // Add custom jwt validation to OWIN pipeline
            app.UseCustomJwtAuthentication(PublicKeyCertificate, Issuers, Audiences);

            // Setup Dependency injection
            var services = new ServiceCollection();

            // Add all ApiControllers in this assembly
            var types = typeof(Startup).Assembly.GetExportedTypes().Where(t =>
                                                                          typeof(ApiController).IsAssignableFrom(t) &&
                                                                          !t.IsAbstract &&
                                                                          !t.IsGenericTypeDefinition &&
                                                                          t.Name.EndsWith("Controller", StringComparison.Ordinal));

            foreach (var type in types)
            {
                services.AddTransient(type);
            }

            // Manually add a controller
            //services.AddTransient<TestController>();

            // Add services need for controllers
            services.AddSingleton <ITestStore>(new TestStore(new Dictionary <string, string>()
            {
                { "stuff", "production" }
            }));

            // Make overwriteable configuration for testing
            CustomServiceConfiguration(services);

            var config = new HttpConfiguration
            {
                DependencyResolver = new DefaultDependencyResolver(services.BuildServiceProvider()),
            };

            // WebApi logging
            var traceWriter = config.EnableSystemDiagnosticsTracing();

            traceWriter.IsVerbose    = true;
            traceWriter.MinimumLevel = TraceLevel.Debug;

            // Use attibute based routing
            config.MapHttpAttributeRoutes();

            // Make overwriteable configuration for testing
            CustomHttpConfiguration(config);

            // Enable WebAPI support
            app.UseWebApi(config);
        }
Esempio n. 16
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var auth = Container.Kernel.Get<AuthenticationService>();

            // Setup telemetry
            var instrumentationKey = config.Current.AppInsightsInstrumentationKey;
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
            }

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuther;
            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            {
                // Configure cookie auth now
                localUserAuther.Startup(config, app);
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                .Authenticators
                .Where(p => !String.Equals(
                    p.Key,
                    Authenticator.GetName(typeof(LocalUserAuthenticator)),
                    StringComparison.OrdinalIgnoreCase))
                .Select(p => p.Value);
            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app);
            }
        }
Esempio n. 17
0
        public void Configuration(IAppBuilder appBuilder)
        {
            // install logging
            XmlConfigurator.Configure();

            bool isValidConfig;

            try
            {
                EnsureAssembliesLoaded();

                // configure container
                var containerBuilder = new WindsorContainerBuilder();

                Container = containerBuilder.Build();

                ConfigurationSpecificRegistration();

                isValidConfig = true;
            }
            catch (Exception e)
            {
                // we swallow the container exceptions so we can still return a valid api with a status of 500. c.f. (ODS-3240)
                Logger.Warn("The container could not be built.");
                Logger.Error(e);
                isValidConfig = false;
            }

            appBuilder.SetLoggerFactory(new Log4NetLoggerFactory());

            if (isValidConfig)
            {
                Logger.Info("Starting ODS/API with a valid container.");

                appBuilder
                .Use <RemoveServerHeaderMiddleware>()
                .UseWebApi(Container.Resolve <HttpConfiguration>());

                // invoke any external tasks if they are installed
                foreach (var externalTask in Container.ResolveAll <IExternalTask>())
                {
                    Logger.Info($"Executing task {externalTask.GetType().Name}.");
                    externalTask.Execute();
                }
            }
            else
            {
                // Invalid windsor container
                Logger.Info("Starting ODS/API to redirect to a 500.");

                appBuilder
                .Use <InvalidWindsorContainerMiddleware>();
            }

            Logger.Info("ODS/Api is running.");
        }
Esempio n. 18
0
        private void Startup(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.DependencyResolver = new MefDependencyResolver(_container);

            appBuilder.SetLoggerFactory(new LoggerFactory());
            appBuilder.UseWebApi(config);
        }
Esempio n. 19
0
 private static void Configure(IAppBuilder app)
 {
     app.SetLoggerFactory(new SerilogWeb.Owin.LoggerFactory(Log.Logger));
     // ReSharper disable once RedundantArgumentDefaultValue
     app.UseSerilogRequestContext("RequestId");
     app.UseImpostor(
         new YamlSettingsParser()
         .Parse(File.ReadAllText("Settings.yaml"))
         );
 }
Esempio n. 20
0
        public void Configuration(IAppBuilder app)
        {
            // register assemblies
            AutofacAssemblyStore.LoadAssembly("Brandscreen.Framework");
            AutofacAssemblyStore.LoadAssembly("Brandscreen.Core");
            AutofacAssemblyStore.LoadAssembly(Assembly.GetExecutingAssembly());

            // create and activate host
            _host = HostStarter.CreateHost();
            _host.Activate(); // Note: HostEventsHandler will be called

            // ensure http configuration
            InitializeHttp(_host);

            // setting logger factory so it can do logging via NLog
            app.SetLoggerFactory(_host.LifetimeScope.Resolve <ILoggerFactory>());

            // handling begin and end request events
            app.Use(async(context, next) =>
            {
                _host.BeginRequest(); // begin request

                try
                {
                    await next();
                }
                catch (OperationCanceledException ex)
                {
                    var logger = app.CreateLogger(GetType());
                    logger.WriteWarning(ex.Message);
                }
                catch (Exception ex)
                {
                    var logger = app.CreateLogger(GetType());
                    logger.WriteError("owin error", ex);
                    throw;
                }
                finally
                {
                    _host.EndRequest(); // end request
                }
            });

            // handling application end event
            var properties = new AppProperties(app.Properties);

            properties.OnAppDisposing.Register(() => _host.Terminate()); // end app

            // setup autofac middleware
            app.UseAutofacMiddleware(_host.LifetimeScope); // IOwinContext is registered by autofac when calling this

            // setup
            ConfigureMvc(app, _host);
            ConfigureApi(app, _host);
        }
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());
            //app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" });
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            // turn off any default mapping on the JWT handler
            //app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            //{
            //    Authority = "http://localhost:5001",
            //    RequiredScopes = new[] { "api" },

            //    ClientId = "api",
            //    ClientSecret = "secret",
            //    //ValidationMode=ValidationMode.Both,
            //    ValidationMode = ValidationMode.ValidationEndpoint,
            //    DelayLoadMetadata = true
            //});

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:5000",
                RequiredScopes = new[] { "api" },

                DelayLoadMetadata = true
            });


            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            app.UseWebApi(config);

            //Federado
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = "Cookies"
            //});

            //app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            //{
            //    MetadataAddress = "http://localhost:5000/wsfederation",
            //    Wtrealm = "urn:owinrp",

            //    SignInAsAuthenticationType = "Cookies"
            //});
        }
Esempio n. 22
0
        /// <summary>
        /// Registers the Web API.
        /// </summary>
        /// <param name="appBuilder">The application builder.</param>
        private void RegisterWebApi(IAppBuilder appBuilder)
        {
            // enable autofac in middlware
            appBuilder.UseAutofacLifetimeScopeInjector(this.AutofacContainer);

            appBuilder.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // configure the web api
            var httpConfig = this.ConfigureWebApi();

            appBuilder.UseWebApi(httpConfig);
        }
Esempio n. 23
0
        public void Configuration(IAppBuilder app)
        {
            var httpConfiguration = new HttpConfiguration
                {
                    DependencyResolver = new AutofacWebApiDependencyResolver(_lifetimeScope)
                };
            httpConfiguration.MapHttpAttributeRoutes();

            app.SetLoggerFactory(new OwinLoggerFactory(_logger));
            app.Use<LoggerMiddleware>(new LoggerMiddlewareOptions(t => _logger.ForContext(t)));
            app.Use<PluginAuthMiddleware>(new PluginAuthMiddlewareOptions(t => _logger.ForContext(t)));
            app.UseAutofacMiddleware(_lifetimeScope);
            app.UseAutofacWebApi(httpConfiguration);
            app.UseWebApi(httpConfiguration);
        }
Esempio n. 24
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public void Configuration(IAppBuilder app)
        {
            // Tune ServicePointManager
            // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx)
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;

            // Register IoC
            app.UseAutofacInjection();
            var dependencyResolver = DependencyResolver.Current;

            // Register Elmah
            var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver);
            ServiceCenter.Current = _ => elmahServiceCenter;

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            // Catch unobserved exceptions from threads before they cause IIS to crash:
            TaskScheduler.UnobservedTaskException += (sender, exArgs) =>
            {
                // Send to ELMAH
                try
                {
                    HttpContext current = HttpContext.Current;
                    if (current != null)
                    {
                        var errorSignal = ErrorSignal.FromContext(current);
                        if (errorSignal != null)
                        {
                            errorSignal.Raise(exArgs.Exception, current);
                        }
                    }
                }
                catch (Exception)
                {
                    // more tragedy... swallow Exception to prevent crashing IIS
                }

                exArgs.SetObserved();
            };

            HasRun = true;
        }
Esempio n. 25
0
        public void Configuration(IAppBuilder app)
        {
            var httpConfiguration = new HttpConfiguration
            {
                DependencyResolver = new AutofacWebApiDependencyResolver(_lifetimeScope)
            };

            httpConfiguration.MapHttpAttributeRoutes();

            app.SetLoggerFactory(new OwinLoggerFactory(_logger));
            app.Use <LoggerMiddleware>(new LoggerMiddlewareOptions(t => _logger.ForContext(t)));
            app.Use <PluginAuthMiddleware>(new PluginAuthMiddlewareOptions(t => _logger.ForContext(t)));
            app.UseAutofacMiddleware(_lifetimeScope);
            app.UseAutofacWebApi(httpConfiguration);
            app.UseWebApi(httpConfiguration);
        }
Esempio n. 26
0
        public void Configure(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            var config = new HttpConfiguration();

            var services = config.Services;

            if (services == null)
            {
                throw new InvalidOperationException();
            }

            Configuration.Cors.Select(configuration => configuration.AsCorsOptions())
            ?.ToList()
            .ForEach(corsOptions => appBuilder.UseCors(corsOptions));

            var constraintResolver = new DefaultInlineConstraintResolver();

            constraintResolver.ConstraintMap?.Add(nameof(AdminActions), typeof(AdminActionsConstraint));
            constraintResolver.ConstraintMap?.Add(nameof(LookupKey), typeof(LookupKey.Constraint));
            constraintResolver.ConstraintMap?.Add(nameof(ChatMessage), typeof(ChatMessage.Constraint));

            // Map routes
            config.MapHttpAttributeRoutes(constraintResolver, new VersionedRouteProvider());
            config.DependencyResolver = new IntersectServiceDependencyResolver(Configuration, config);

            // Make JSON the default response type for browsers
            config.Formatters?.JsonFormatter?.Map("accept", "text/html", "application/json");

            if (Configuration.DebugMode)
            {
                appBuilder.SetLoggerFactory(new IntersectLoggerFactory());
            }

            if (Configuration.RequestLogging)
            {
                appBuilder.Use <IntersectRequestLoggingMiddleware>(Configuration.RequestLogLevel);
            }

            appBuilder.Use <IntersectThrottlingMiddleware>(
                Configuration.ThrottlePolicy, null, Configuration.FallbackClientKey, null
                );

            AuthenticationProvider.Configure(appBuilder);

            appBuilder.UseWebApi(config);
        }
Esempio n. 27
0
        public override void Configuration(IAppBuilder appBuilder)
        {
            InitializeContainer(Container);
            InstallWebApiComponents();

            // TODO: GKM - Profiles - Need to register additional controllers for the test profiles
            // Controllers
            Container.Register(
                Classes.FromAssemblyContaining <Marker_EdFi_Ods_Profiles_Test>()
                .BasedOn <ApiController>()
                .LifestyleTransient());

            InstallConfigurationSpecificInstaller(Container);

            // TODO: GKM - No NHibernate desired for testing
            // NHibernate initialization
            //(new NHibernateConfigurator()).Configure(Container);

            var httpConfig = new HttpConfiguration {
                DependencyResolver = Container.Resolve <IDependencyResolver>()
            };

            // Replace the default controller selector with one based on the final namespace segment (to enable support of Profiles)
            httpConfig.Services.Replace(
                typeof(IHttpControllerSelector),
                new ProfilesAwareHttpControllerSelector(
                    httpConfig,
                    Container.Resolve <IProfileResourceNamesProvider>(),
                    Container.Resolve <ISchemaNameMapProvider>()));

            //httpConfig.EnableSystemDiagnosticsTracing();
            httpConfig.EnableCors(new EnableCorsAttribute("*", "*", "*", "*"));
            ConfigureFormatters(httpConfig);
            ConfigureRoutes(httpConfig);
            ConfigureDelegatingHandlers(httpConfig, Container.ResolveAll <DelegatingHandler>());
            RegisterFilters(httpConfig);
            RegisterAuthenticationProvider(Container);

            appBuilder.UseWebApi(httpConfig);

            XmlConfigurator.Configure();
            appBuilder.SetLoggerFactory(new Log4NetLoggerFactory());

            InstallOpenApiMetadata(Container);
        }
Esempio n. 28
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:5000",
                RequiredScopes = new[] { "api" },

                DelayLoadMetadata = true
            });

            app.UseWebApi(config);
        }
Esempio n. 29
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get <ConfigurationService>();
            var auth   = Container.Kernel.Get <AuthenticationService>();

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuther;

            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            {
                // Configure cookie auth now
                localUserAuther.Startup(config, app);
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName         = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan     = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                                   .Authenticators
                                   .Where(p => !String.Equals(
                                              p.Key,
                                              Authenticator.GetName(typeof(LocalUserAuthenticator)),
                                              StringComparison.OrdinalIgnoreCase))
                                   .Select(p => p.Value);

            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app);
            }
        }
Esempio n. 30
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            app.Use(async(ctx, next) =>
            {
                //Example for correlating logs, track source address
                CallContext.LogicalSetData("correlationIdentifier", ctx.Environment["owin.RequestId"]);
                CallContext.LogicalSetData("sourceInfo", $"{ctx.Request.RemoteIpAddress}:{ctx.Request.RemotePort}");
                await next();
                CallContext.FreeNamedDataSlot("correlationIdentifier");
                CallContext.FreeNamedDataSlot("sourceInfo");
            })
            .UseErrorPage()
            .UseOioIdwsAuthentication(new OioIdwsAuthenticationOptions
            {
                TokenProvider = new RestTokenProvider(new Uri("https://digst.oioidws.rest.as:10001/accesstoken"), CertificateUtil.GetCertificate("1F0830937C74B0567D6B05C07B6155059D9B10C7"))
            })
            .Use <MyService>();
        }
Esempio n. 31
0
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.SetLoggerFactory(new ConsoleLogger.Factory());
#endif

            app.Use((IOwinContext owinContext, Func <Task> next) =>
            {
                owinContext.Environment.Add("saml2.idp", new EntityId(IdpEntityId));
                return(next.Invoke());
            });

            app.SetDefaultSignInAsAuthenticationType("SamlCookie");
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "SamlCookie",
                CookieSameSite     = SameSiteMode.None
            });
            app.UseSaml2Authentication(GetSaml2AuthenticationOptions());
        }
Esempio n. 32
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var auth = Container.Kernel.Get<AuthenticationService>();

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuther;
            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            {
                // Configure cookie auth now
                localUserAuther.Startup(config, app);
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                .Authenticators
                .Where(p => !String.Equals(
                    p.Key,
                    Authenticator.GetName(typeof(LocalUserAuthenticator)),
                    StringComparison.OrdinalIgnoreCase))
                .Select(p => p.Value);

            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app);
            }
        }
Esempio n. 33
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureNinject(app);

            // Get config
            var config = Container.Kernel.Get <ConfigurationService>();
            var auth   = Container.Kernel.Get <AuthenticationService>();

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            ConfigureAuth(config, auth, app);
            ConfigureWebApi(app);
        }
Esempio n. 34
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("Default", "api/{controller}");

            app.UseHawkAuthentication(new HawkAuthenticationOptions
            {
                Credentials = (id) =>
                {
                    return Task.FromResult(new HawkCredential
                    {
                        Id = "dh37fgj492je",
                        Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                        Algorithm = "hmacsha256",
                        User = "******"
                    });
                }
            });
            app.UseWebApi(config);
        }
Esempio n. 35
0
        public void Configuration(IAppBuilder app)
        {
            #region WebApi (Web Framework in OWIN terminology)

            HttpConfiguration webApiConfig = new HttpConfiguration();
            WebApiConfig.Configure(webApiConfig);

            #endregion

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                TicketDataFormat   = new TicketDataFormat(
                    new MachineKeyDataProtector(
                        "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
                        DefaultAuthenticationTypes.ApplicationCookie,
                        "v1"))
            });
            app.UseWebApi(webApiConfig);

            app.SetLoggerFactory(new Infrastructure.Owin.LoggerFactory());
        }
Esempio n. 36
0
        public static void Configure(IAppBuilder app)
        {
            app.UseWindsorContainer("windsor.config");
            app.UseWindsorMiddleWare();

            var container = app.GetWindsorContainer();

            container.Register(
                Component.For <IAuthenticationManager>()
                .FromOwinContext()
                .LifestyleTransient()
                );

            var loggerFactory = container.Resolve <ILoggerFactory>();

            app.SetLoggerFactory(loggerFactory);

            var options = container.Resolve <StaticFileMiddlewareOptions>();

            app.UseStaticFile(options);

            app.UseAesDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.UseWindsorContainer(container);

            app.UseWebApi(config);
        }
Esempio n. 37
0
        public void Configuration(IAppBuilder app)
        {
            app.SetLoggerFactory(new ConsoleLoggerFactory());

            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute("Default", "api/{controller}");

            app.UseHawkAuthentication(new HawkAuthenticationOptions
            {
                Credentials = (id) =>
                {
                    return(Task.FromResult(new HawkCredential
                    {
                        Id = "dh37fgj492je",
                        Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                        Algorithm = "hmacsha256",
                        User = "******"
                    }));
                }
            });
            app.UseWebApi(config);
        }
Esempio n. 38
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var auth = Container.Kernel.Get<AuthenticationService>();

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                //app.UseForceSslWhenAuthenticated(config.Current.SSLPort);

                // Put a middleware at the top of the stack to force the user over to SSL always
                app.UseForceSslAlways(config.Current.SSLPort);
            }

            app.UseBasicAuthentication(new BasicAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = AuthenticationTypes.LocalUser,
            });
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.LocalUser);

            if (config.Current.ForceAuth)
            {
                app.Authorize();
            }

            //// Get the local user auth provider, if present and attach it first
            //Authenticator localUserAuther;
            //if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            //{
            //    // Configure cookie auth now
            //    localUserAuther.Startup(config, app);
            //}

            //// Attach external sign-in cookie middleware
            //app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            //app.UseCookieAuthentication(new CookieAuthenticationOptions()
            //{
            //    AuthenticationType = AuthenticationTypes.External,
            //    AuthenticationMode = AuthenticationMode.Passive,
            //    CookieName = ".AspNet." + AuthenticationTypes.External,
            //    ExpireTimeSpan = TimeSpan.FromMinutes(5)
            //});

            //// Attach non-cookie auth providers
            //var nonCookieAuthers = auth
            //    .Authenticators
            //    .Where(p => !String.Equals(
            //        p.Key,
            //        Authenticator.GetName(typeof(LocalUserAuthenticator)),
            //        StringComparison.OrdinalIgnoreCase))
            //    .Select(p => p.Value);
            //foreach (var auther in nonCookieAuthers)
            //{
            //    auther.Startup(config, app);
            //}
        }
Esempio n. 39
0
        public void Configuration(IAppBuilder app)
        {
            app.UseWindsorContainer("windsor.config");
            var container = app.GetWindsorContainer();

            app.UseWindsorMiddleWare();

            var loggerFactory = container.Resolve<Microsoft.Owin.Logging.ILoggerFactory>();
            app.SetLoggerFactory(loggerFactory);

            var logMiddleware = container.Resolve<ConsoleLogMiddleware>();
            app.Use(logMiddleware);

            var options = container.Resolve<StaticFileMiddlewareOptions>();
            app.UseStaticFile(options);
            // identity;
            container.Register(
                Component.For<IAuthenticationManager>().FromOwinContext().LifestyleTransient()
            );

            // authentication
            var dataProtectionProvider = container.Resolve<IDataProtectionProvider>();
            app.SetDataProtectionProvider(dataProtectionProvider);
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider = new CookieAuthenticationProvider {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)
                    )
                }
            });
            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),
            //                // In production mode set AllowInsecureHttp = false
            //                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 = ""
            //});
            ConfigWebApi(app);
        }
Esempio n. 40
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var auth = Container.Kernel.Get<AuthenticationService>();

            // Setup telemetry
            var instrumentationKey = config.Current.AppInsightsInstrumentationKey;
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
            }

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuther;
            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            {
                // Configure cookie auth now
                localUserAuther.Startup(config, app);
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                .Authenticators
                .Where(p => !String.Equals(
                    p.Key,
                    Authenticator.GetName(typeof(LocalUserAuthenticator)),
                    StringComparison.OrdinalIgnoreCase))
                .Select(p => p.Value);
            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app);
            }

            // Catch unobserved exceptions from threads before they cause IIS to crash:
            TaskScheduler.UnobservedTaskException += (sender, exArgs) =>
            {
                // Send to AppInsights
                try
                {
                    var telemetryClient = new TelemetryClient();
                    telemetryClient.TrackException(exArgs.Exception, new Dictionary<string, string>()
                    {
                        {"ExceptionOrigin", "UnobservedTaskException"}
                    });
                }
                catch (Exception)
                {
                    // this is a tragic moment... swallow Exception to prevent crashing IIS
                }

                // Send to ELMAH
                try
                {
                    HttpContext current = HttpContext.Current;
                    if (current != null)
                    {
                        var errorSignal = ErrorSignal.FromContext(current);
                        if (errorSignal != null)
                        {
                            errorSignal.Raise(exArgs.Exception, current);
                        }
                    }
                }
                catch (Exception)
                {
                    // more tragedy... swallow Exception to prevent crashing IIS
                }

                exArgs.SetObserved();
            };
        }
Esempio n. 41
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Tune ServicePointManager
            // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx)
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;

            // Register IoC
            app.UseAutofacInjection(GlobalConfiguration.Configuration);
            var dependencyResolver = DependencyResolver.Current;

            // Register Elmah
            var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver);
            ServiceCenter.Current = _ => elmahServiceCenter;

            // Get config
            var config = dependencyResolver.GetService<IGalleryConfigurationService>();
            var auth = dependencyResolver.GetService<AuthenticationService>();

            // Setup telemetry
            var instrumentationKey = config.Current.AppInsightsInstrumentationKey;
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;

                var telemetryProcessorChainBuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
                telemetryProcessorChainBuilder.Use(next => new TelemetryResponseCodeFilter(next));

                // Note: sampling rate must be a factor 100/N where N is a whole number
                // e.g.: 50 (= 100/2), 33.33 (= 100/3), 25 (= 100/4), ...
                // https://azure.microsoft.com/en-us/documentation/articles/app-insights-sampling/
                var instrumentationSamplingPercentage = config.Current.AppInsightsSamplingPercentage;
                if (instrumentationSamplingPercentage > 0 && instrumentationSamplingPercentage < 100)
                {
                    telemetryProcessorChainBuilder.UseSampling(instrumentationSamplingPercentage);
                }

                telemetryProcessorChainBuilder.Build();
            }

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                app.UseForceSslWhenAuthenticated(config.Current.SSLPort);
            }

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuthenticator;
            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuthenticator))
            {
                // Configure cookie auth now
                localUserAuthenticator.Startup(config, app).Wait();
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                .Authenticators
                .Where(p => !String.Equals(
                    p.Key,
                    Authenticator.GetName(typeof(LocalUserAuthenticator)),
                    StringComparison.OrdinalIgnoreCase))
                .Select(p => p.Value);
            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app).Wait();
            }

            // Catch unobserved exceptions from threads before they cause IIS to crash:
            TaskScheduler.UnobservedTaskException += (sender, exArgs) =>
            {
                // Send to AppInsights
                try
                {
                    var telemetryClient = new TelemetryClient();
                    telemetryClient.TrackException(exArgs.Exception, new Dictionary<string, string>()
                    {
                        {"ExceptionOrigin", "UnobservedTaskException"}
                    });
                }
                catch (Exception)
                {
                    // this is a tragic moment... swallow Exception to prevent crashing IIS
                }

                // Send to ELMAH
                try
                {
                    HttpContext current = HttpContext.Current;
                    if (current != null)
                    {
                        var errorSignal = ErrorSignal.FromContext(current);
                        if (errorSignal != null)
                        {
                            errorSignal.Raise(exArgs.Exception, current);
                        }
                    }
                }
                catch (Exception)
                {
                    // more tragedy... swallow Exception to prevent crashing IIS
                }

                exArgs.SetObserved();
            };

            HasRun = true;
        }