private void ConfigureFileServer(IAppBuilder app, HostConfig config)
        {
            // use a file server to serve all static content (js, css, content, html, ...) and also configure default files (eg: index.html to be the default entry point)

            // create file system that will locate the files
            var fileSystem = AggregateFileSystem.FromWebUiPhysicalPaths(config.RootDirectory);

            // setup default documents
            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileSystem = fileSystem,
                DefaultFileNames = new List<string>
                {
                    "views/index.html"
                }
            });


            // start file server to share website static content
            // wrapper around: StaticFiles + DefaultFiles + DirectoryBrowser
            var fileServerOptions = new FileServerOptions
            {
                EnableDirectoryBrowsing = false,
                FileSystem = fileSystem,
            };

            fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileServerContentTypeProvider();

            app.UseFileServer(fileServerOptions);
        }
Esempio n. 2
0
 public void Configuration(IAppBuilder app)
 {
     string strUseRedis = CloudConfigurationManager.GetSetting("UseRedis") ?? "false";
     bool useRedis = bool.Parse(strUseRedis);
     var dependencyResolver = new UnityDependencyResolver();
     UnityWireupConfiguration.WireUp(dependencyResolver);
     GlobalHost.DependencyResolver = dependencyResolver;
     var options = new CookieAuthenticationOptions()
     {
         AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
         LoginPath = new PathString("/"),
         LogoutPath = new PathString("/")
     };
     app.UseCookieAuthentication(options);
     app.Use(async (context, next) =>
     {
         if (context.Request.Path.Value.Equals("/") ||
         context.Request.Path.Value.StartsWith("/public", StringComparison.CurrentCultureIgnoreCase))
         {
             await next();
         }
         else if (context.Request.User == null || !context.Request.User.Identity.IsAuthenticated)
         {
             context.Response.StatusCode = 401;
         }
         else
         {
             await next();
         }
     });
     HttpConfiguration webApiConfiguration = new HttpConfiguration();
     webApiConfiguration.DependencyResolver = dependencyResolver;
     webApiConfiguration.MapHttpAttributeRoutes();
     app.UseWebApi(webApiConfiguration);
     RedisConfiguration redisConfiguration = dependencyResolver.Resolve<RedisConfiguration>();
     if (redisConfiguration.UseRedis)
     {
         GlobalHost.DependencyResolver.UseRedis(redisConfiguration.HostName, redisConfiguration.Port, redisConfiguration.Password, redisConfiguration.EventKey);
     }
     app.MapSignalR();
     var sharedOptions = new SharedOptions()
     {
         RequestPath = new PathString(string.Empty),
         FileSystem =
             new PhysicalFileSystem(".//public//content")
     };
     app.UseDefaultFiles(new Microsoft.Owin.StaticFiles.DefaultFilesOptions(sharedOptions)
     {
         DefaultFileNames = new List<string>() { "index.html" }
     });
     app.UseStaticFiles("/public");
     app.UseStaticFiles("/content");
     app.UseStaticFiles("/scripts");
     app.UseStaticFiles("/styles");
     app.UseStaticFiles(new StaticFileOptions(sharedOptions));
 }
Esempio n. 3
0
        public void CustomDefaultFileConfiguration(IAppBuilder app)
        {
            var options = new DefaultFilesOptions() { DefaultFileNames = new string[] { "TextFile1.txt" }, FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1") };
            app.UseDefaultFiles(options);

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1")
            });
        }
Esempio n. 4
0
 private void ConfigureManager(IAppBuilder appBuilder)
 {
     var fileSystem = new PhysicalFileSystem("./Portal");
     appBuilder.UseDefaultFiles(new DefaultFilesOptions
     {
         DefaultFileNames = new[] {"index.html"},
         FileSystem = fileSystem
     });
     appBuilder.UseStaticFiles(new StaticFileOptions
     {
         RequestPath = new PathString(""),
         FileSystem = fileSystem,
         ServeUnknownFileTypes = true,
     });
 }
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            // If you want to enable ASP.NET Web API:
            // 1) Install Microsoft.AspNet.WebApi.Owin NuGet package. (ex."PM> Install-Package Microsoft.AspNet.WebApi.Owin")
            // 2) Import "System.Web.Http" namespace. (insert "using System.Web.Http;" at head of this file)
            // 3) Uncomment lines below.
            // After this, you can implement API controllers with attribute routing.

            //// Confiure ASP.NET Web API
            //var config = new HttpConfiguration();
            //config.MapHttpAttributeRoutes();
            //app.UseWebApi(config);

            // Configure OWIN Static Files middleware to provide contents from embedded resources.
            var appSettings = ConfigurationManager.AppSettings;
            if (appSettings["use:OwinStaticFiles"] != "false")
            {
                var fileSystem = new EmbeddedResourceFileSystem(this.GetType().Assembly, this.GetType().Namespace);

                app.UseDefaultFiles(new DefaultFilesOptions
                {
                    FileSystem = fileSystem,
                    DefaultFileNames = new List<string> { "index.html" }
                });

                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = fileSystem,
                    ServeUnknownFileTypes = true,
                    OnPrepareResponse = context =>
                    {
                        var headers = context.OwinContext.Response.Headers;

                        // If you use AngulaJS at client side, it's recomended about
                        // appending "Cache-control: no-cache" header in response to avoid "cache tatooing".
                        headers.Add("Cache-control", new[] { "no-cache" });

                        // If you want to determine which content source (embedded resouces via Owin Static Files middleware,
                        // or local file system via IIS) responded, this custom response header will helps you.
                        headers.Add("X-StaticFile-Hanler", new[] { "OwinStaticFiles" });
                    }
                });
            }
        }
Esempio n. 6
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration configuration = new HttpConfiguration();

            // SignalR
            app.MapSignalR();

            //// Make sure we're shipping our own provider
            //var dependencyResolver = Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver;
            //dependencyResolver.Register(typeof(Microsoft.AspNet.SignalR.Hubs.IHubDescriptorProvider), () => new EcoHubDescriptorProvider(dependencyResolver));

            // Web API
            app.UseWebApi(configuration);

            // Static files
            var staticFilesDirectory = _webRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            if (!Directory.Exists(staticFilesDirectory))
                throw new InvalidOperationException($"Could not find webroot directory at {staticFilesDirectory}. Please check your installation.");

            var fileSystem = new PhysicalFileSystem(staticFilesDirectory);
            var requestPath = PathString.Empty;

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                DefaultFileNames = new List<string> { "index.html" },
                FileSystem = fileSystem,
                RequestPath = requestPath
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = fileSystem,
                RequestPath = requestPath,
                ServeUnknownFileTypes = false
            });

            app.Run(async (context) =>
            {
                var response = context.Response;
                response.StatusCode = 404;
                response.ReasonPhrase = "Not Found";
                await response.WriteAsync(@"<!DOCTYPE html><html><head><title>404 - Not Found</title></head><body><h1>404 - Not Found</h1></body></html>");
            });
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            // ioc container
            ResolveContainer();

            // init database
            InitDatabase();

            // synchronize repositories
            container.Resolve<Services.RepositoryService>().Init();

            // authorization
            app.Use<AuthenticationClientCertListMiddleware>(container.Resolve<AuthenticationClientCertListOptions>());

#if DEBUG
            app.UseErrorPage();
#endif

            // setup config
            var config = new System.Web.Http.HttpConfiguration();

            // enable Castle Windsor
            config.Services.Replace(typeof(System.Web.Http.Dispatcher.IHttpControllerActivator), new WindsorCompositionRoot(this.container));

            // routing
            SetUpRouting(config);

            // static files (UI)
            var staticFileOptions = new Microsoft.Owin.StaticFiles.StaticFileOptions() { 
                FileSystem = new EmbeddedResourceFileSystem(this.GetType().Assembly, "DevUpdater.Server.StaticContent")
            };
            app.UseDefaultFiles(new DefaultFilesOptions() { FileSystem = staticFileOptions.FileSystem });
            app.UseStaticFiles(staticFileOptions);

            // web api stuff
            app.UseWebApi(config);
        }
Esempio n. 8
0
 public void DefaultFile(IAppBuilder app)
 {
     app.Use((context, next) => { context.Response.Headers["PassedThroughOWIN"] = "True"; return next(); });
     app.UseDefaultFiles(new DefaultFilesOptions()
     {
         DefaultFileNames = new[] { "TextFile.txt" }
     });
     app.Run(context => { context.Response.StatusCode = 402; return context.Response.WriteAsync(context.Request.Path.Value); });
 }
Esempio n. 9
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
            app.UseWebApi(ConfigureWebApi());

            var staticFileOptions = new StaticFileOptions
            {
                RequestPath = new PathString("/web"),
                FileSystem = new PhysicalFileSystem(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "webdir"))
            };
            app.UseDefaultFiles(new DefaultFilesOptions
            {
                RequestPath = staticFileOptions.RequestPath,
                FileSystem = staticFileOptions.FileSystem,
            });
            app.UseStaticFiles(staticFileOptions);
        }
Esempio n. 10
0
 public void FolderWithDefaultFileConfiguration(IAppBuilder app)
 {
     app.UseDefaultFiles();
     app.UseStaticFiles();
 }
Esempio n. 11
0
        public void Configuration(IAppBuilder builder)
        {
            var rootDirectory = Environment.CurrentDirectory;
            var loginDirectory = Path.Combine(rootDirectory, "login");

            var fs = new PhysicalFileSystem(rootDirectory);
            var loginFs = new PhysicalFileSystem(loginDirectory);

            var dfo = new DefaultFilesOptions();
            dfo.DefaultFileNames.Add("index.html");
            dfo.FileSystem = fs;

            var sfo = new StaticFileOptions
                      {
                          FileSystem = fs
                      };
            var loginSfo = new StaticFileOptions
                           {
                               FileSystem = loginFs
                           };

            builder.SetDataProtectionProvider(new DpapiDataProtectionProvider());
            var formsAuthenticationProvider = new FormsAuthenticationProvider();

            formsAuthenticationProvider.OnValidateLogin = context =>
            {
                Console.WriteLine("Validating Login");
                Console.WriteLine("================");
                Console.WriteLine("  Context.AuthType: " + context.AuthenticationType);
                Console.WriteLine("  Context.Identity: " + (context.Identity != null ? context.Identity.Name : "Not set"));
                Console.WriteLine("  Context.Environment:");

                var response = new OwinResponse(context.Environment);

                if (LoginContext.GetIsLoginRequest(context.Environment))
                {
                    // Need to retrieve username and password from environment b/c it doesn't
                    // come through in the context (even though the context constructor accepts them)

                    var username = context.Environment["formsauthn.username"].ToString();
                    var password = context.Environment["formsauthn.password"].ToString();
                    var remember = bool.Parse(context.Environment["formsauthn.remember"].ToString());

                    Console.WriteLine("  Request.Username: "******"  Request.Password: "******"  Request.Remember: " + remember);

                    if (username == password)
                    {
                        var identity = new ClaimsIdentity(
                            new GenericIdentity(username, context.AuthenticationType),
                            new[]
                            {
                                new Claim(ClaimTypes.IsPersistent, remember.ToString())
                            }
                            );

                        // I assumed that this would take care of populating the cookie for me... but not so much.
                        context.Signin(identity);

                        var msg = "Access granted.";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length);
                    }
                    else
                    {
                        var msg = "Access denied.  Try with username=password";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length);
                    }
                }
                else
                {
                    foreach (var item in context.Environment)
                    {
                        Console.WriteLine("  {0}={1}",
                                          item.Key,
                                          item.Value != null
                                              ? (item.Value is string ? (string) item.Value : item.Value.GetType().FullName)
                                              : "Not set"
                            );
                    }
                }

                return response.Body.WriteAsync(new byte[] { }, 0, 0);
            };

            builder.UseFormsAuthentication(
                new FormsAuthenticationOptions
                {
                    CookieHttpOnly = true,
                    CookieName = "AuthCookie",
                    CookiePath = "/",
                    CookieSecure = false,
                    LoginPath = "/login/",
                    ExpireTimeSpan = TimeSpan.FromHours(1),
                    ReturnUrlParameter = "returnUrl",
                    SlidingExpiration = true,
                    Provider = formsAuthenticationProvider
                }
            );
            builder.UseApplicationSignInCookie();
            builder.UseDefaultFiles(dfo);
            builder.UseErrorPage();
            builder.MapPath("/login", loginBuilder => loginBuilder.UseProcessLoginPostback(formsAuthenticationProvider).UseStaticFiles(loginSfo));
            builder.UseDenyAnonymous().UseStaticFiles(sfo);
        }