Exemplo n.º 1
0
 void AssertAllowed(string origin, System.Web.Cors.CorsPolicy cp)
 {
     Assert.IsTrue(cp.AllowAnyHeader);
     Assert.IsTrue(cp.AllowAnyMethod);
     Assert.AreEqual(1, cp.Origins.Count);
     CollectionAssert.Contains(cp.Origins.ToArray(), origin);
 }
 void AssertAllowed(string origin, CorsPolicy cp)
 {
     cp.AllowAnyHeader.Should().BeTrue();
     cp.AllowAnyMethod.Should().BeTrue();
     cp.Origins.Count.Should().Be(1);
     cp.Origins.Should().Contain(origin);
 }
Exemplo n.º 3
0
 void AssertAllowed(string origin, CorsPolicy cp)
 {
     cp.AllowAnyHeader.Should().BeTrue();
     cp.AllowAnyMethod.Should().BeTrue();
     cp.Origins.Count.Should().Be(1);
     cp.Origins.Should().Contain(origin);
 }
Exemplo n.º 4
0
        /// <summary>Configures the authentication.
        /// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864</summary>
        /// <param name="app">The app.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            // Changing this setting requires a website restart
            var corsOrigin = BootStrapper.GetApplicationSetting("Cors_Origin", string.Empty);

            if (!corsOrigin.IsBlank())
            {
                var policy = new CorsPolicy
                {
                    AllowAnyHeader      = true,
                    AllowAnyMethod      = true,
                    AllowAnyOrigin      = corsOrigin.Equals("*"),
                    SupportsCredentials = true
                };
                if (!policy.AllowAnyOrigin)
                {
                    corsOrigin.Split(',').ForEach(origin => policy.Origins.Add(origin.Trim()));
                }

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

            app.CreatePerOwinContext(IdentityDbContext.Create);
            app.CreatePerOwinContext <IdentityUserManager>(IdentityUserManager.Create);
            app.CreatePerOwinContext <IdentitySignInManager>(IdentitySignInManager.Create);

            app.UseKentorOwinCookieSaver();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = SecurityOptions.IdentityServerOptions.IssuerUri,
                RequiredScopes = new[] { SecurityOptions.Scope },
                NameClaimType  = Constants.ClaimTypes.PreferredUserName,
                RoleClaimType  = Constants.ClaimTypes.Role
            });


            app.UseCookieAuthentication(SecurityOptions.CookieOptions);

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Map("/identity", identityApp => { identityApp.UseIdentityServer(SecurityOptions.IdentityServerOptions); });

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            // app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            // app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
 System.Web.Cors.CorsPolicy Allow(string origin)
 {
     var policy = new System.Web.Cors.CorsPolicy
     {
         AllowAnyHeader = true,
         AllowAnyMethod = true,
     };
     policy.Origins.Add(origin);
     return policy;
 }
        System.Web.Cors.CorsPolicy Allow(string origin)
        {
            var p = new System.Web.Cors.CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
            };

            p.Origins.Add(origin);
            return(p);
        }
Exemplo n.º 7
0
        private Task <System.Web.Cors.CorsPolicy> ResolvePolicy()
        {
            var corsPolicy = new System.Web.Cors.CorsPolicy()
            {
                AllowAnyMethod      = true,
                AllowAnyHeader      = true,
                SupportsCredentials = true
            };

            corsPolicy.Origins.Add("http://ng2a-hneu-web-ui.azurewebsites.net");
            corsPolicy.Origins.Add("http://localhost:3000");

            return(Task.FromResult(corsPolicy));
        }
Exemplo n.º 8
0
        public static void SetupCorsPolicy(this IAppBuilder app)
        {
            var corsPolicy = new System.Web.Cors.CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                AllowAnyOrigin = true
            };

            corsPolicy.GetType().GetProperty(nameof(corsPolicy.ExposedHeaders)).SetValue(corsPolicy, CorsHelper.GetExposedHeaders());

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            });
        }
Exemplo n.º 9
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                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 <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 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 = ""
            //});
            var policy = new System.Web.Cors.CorsPolicy()
            {
                AllowAnyHeader      = false,
                AllowAnyMethod      = true,
                SupportsCredentials = true
            };

            policy.Origins.Add("http://localhost:4200");               //be sure to include the port: example: "http://localhost:8081"
            policy.Origins.Add("http://localhost");                    //be sure to include the port:
            policy.Origins.Add("http://octo.computerwebservices.net"); //be sure to include the port:

            app.UseCors(new Microsoft.Owin.Cors.CorsOptions {
                PolicyProvider = new Microsoft.Owin.Cors.CorsPolicyProvider
                {
                    PolicyResolver = a => Task.FromResult(policy)
                }
            });

            app.MapSignalR();
        }
Exemplo n.º 10
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 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);

            //Enable global CORS Permissions
            //Info: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
            var corsPolicy = new System.Web.Cors.CorsPolicy()
            {
                AllowAnyHeader = true, AllowAnyMethod = true, AllowAnyOrigin = false,
            };
            string clientURL = ConfigurationManager.AppSettings["clientURL"];

            corsPolicy.Origins.Add(clientURL);
            //app.UseCors(CorsOptions.AllowAll);
            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            });

            // 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 = ""
            //});
        }
Exemplo n.º 11
0
        public void Configuration(IAppBuilder app)
        {
            // Dependency injection settings
            var container = new UnityContainer();
            var config    = WebApiConfig.Register(container);

            app.Use <LoggingMiddleware>();
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requestsit
            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            /*var myProvider = new AuthorizationServerProvider(config.DependencyResolver as IServiceBus);
             * OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
             * {
             *  AllowInsecureHttp = true,
             *  TokenEndpointPath = new PathString("/token"),
             *  AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),   // OAuth token valid 1 day
             *  Provider = myProvider,
             *  RefreshTokenProvider = new SimpleRefreshTokenProvider()
             * };
             * app.UseOAuthAuthorizationServer(options);
             * app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());*/
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                //AllowedAudiences = new[] { "KL²", "KL² Web Admin", "KL² Tablet" },
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = JwtTokenProvider._jwtSecret.ToSymmetricSecurityKey(),
                    ValidIssuer      = JwtTokenProvider._appDomain,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(0)
                }
            });

            app.UseWebApi(config);

            // Branch the pipeline here for requests that start with "/signalr"
            app.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.
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR(SignalRConfig.Register(container));
            });

            //app.MapSignalR(SignalRConfig.Register(container));

            var corsPolicy = new System.Web.Cors.CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                AllowAnyOrigin = true
            };

            // ExposedHeaders has a private setter for some reason so one must use reflection to set it.
            corsPolicy.GetType()
            .GetProperty(nameof(corsPolicy.ExposedHeaders))
            .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());

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


            app.UseTus(context => new DefaultTusConfiguration
            {
                Store   = ((UnityResolver)config.DependencyResolver).Resolve <IFileProvider>().GetTusStore(),
                UrlPath = "/files",
                Events  = new Events
                {
                    OnFileCompleteAsync = async ctx =>
                    {
                        if (ctx.Store is ITusReadableStore readableStore)
                        {
                            var fileProvider = ((UnityResolver)config.DependencyResolver).Resolve <IFileProvider>();

                            var file = await ctx.GetFileAsync();
                            if (file == null)
                            {
                                return;
                            }
                            //await readableStore.GetFileAsync(ctx.FileId, ctx.CancellationToken);
                            var metadata    = await file.GetMetadataAsync(ctx.CancellationToken);
                            string filename = metadata?.ContainsKey("filename") == true ? metadata["filename"].GetString(System.Text.Encoding.UTF8) : file.Id;
                            if (metadata?.ContainsKey("computeHash") == true)
                            {
                                HashAlgorithm murmur128 = MurmurHash.Create128(managed: false);
                                using (var ms = await fileProvider.OpenRead(file.Id, DirectoryEnum.Uploaded))
                                {
                                    var streamHash = murmur128.ComputeHash(ms).ToHashString();
                                    filename       = $"{streamHash}{Path.GetExtension(filename)}";
                                }
                            }
                            // On doit déplacer le fichier vers PublishedFiles en le renommant
                            await fileProvider.Complete(file.Id, filename);
                            // TODO : ajouter une metadata indiquant un traitement avec FFMPEG (encodage vidéo, traitement image)
                            // Supprimer les fichiers temp
                            var tempFiles = await fileProvider.EnumerateFiles(DirectoryEnum.Uploaded, $"{file.Id}.*");
                            foreach (string tmpFile in tempFiles)
                            {
                                await fileProvider.Delete(tmpFile, DirectoryEnum.Uploaded);
                            }

                            fileProvider.WriteAllText($"{fileProvider.UploadedFilesDirectory}/{file.Id}.name", filename);
                        }
                    }
                }
            });
Exemplo n.º 12
0
        public void Configuration(IAppBuilder app)
        {
            var corsPolicy = new System.Web.Cors.CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                AllowAnyOrigin = true
            };

            // ReSharper disable once PossibleNullReferenceException - nameof will cause compiler error if the property does not exist.
            corsPolicy.GetType()
            .GetProperty(nameof(corsPolicy.ExposedHeaders))
            .SetValue(corsPolicy, CorsHelper.GetExposedHeaders());

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

            app.Use(async(context, next) =>
            {
                try
                {
                    await next.Invoke();
                }
                catch (Exception exc)
                {
                    Console.Error.WriteLine(exc);
                }
            });

            app.UseTus(request =>
            {
                return(new DefaultTusConfiguration
                {
                    Store = _tusDiskStore,
                    UrlPath = "/files",
                    OnUploadCompleteAsync = (fileId, store, cancellationToken) =>
                    {
                        Console.WriteLine(
                            $"Upload of {fileId} is complete. Callback also got a store of type {store.GetType().FullName}");
                        // If the store implements ITusReadableStore one could access the completed file here.
                        // The default TusDiskStore implements this interface:
                        // var file = await ((ITusReadableStore)store).GetFileAsync(fileId, cancellationToken);
                        return Task.FromResult(true);
                    },
                    // Set an expiration time where incomplete files can no longer be updated.
                    // This value can either be absolute or sliding.
                    // Absolute expiration will be saved per file on create
                    // Sliding expiration will be saved per file on create and updated on each patch/update.
                    Expiration = _absoluteExpiration
                });
            });

            app.Use(async(context, next) =>
            {
                // All GET requests to tusdotnet are forwared so that you can handle file downloads.
                // This is done because the file's metadata is domain specific and thus cannot be handled
                // in a generic way by tusdotnet.
                if (!context.Request.Method.Equals("get", StringComparison.InvariantCultureIgnoreCase))
                {
                    await next.Invoke();
                    return;
                }

                if (context.Request.Uri.LocalPath.StartsWith("/files/", StringComparison.Ordinal))
                {
                    var fileId = context.Request.Uri.LocalPath.Replace("/files/", "").Trim();
                    if (!string.IsNullOrEmpty(fileId))
                    {
                        var file = await _tusDiskStore.GetFileAsync(fileId, context.Request.CallCancelled);

                        if (file == null)
                        {
                            context.Response.StatusCode = 404;
                            await context.Response.WriteAsync($"File with id {fileId} was not found.", context.Request.CallCancelled);
                            return;
                        }

                        var fileStream = await file.GetContentAsync(context.Request.CallCancelled);
                        var metadata   = await file.GetMetadataAsync(context.Request.CallCancelled);

                        context.Response.ContentType = metadata.ContainsKey("contentType")
                                                        ? metadata["contentType"].GetString(Encoding.UTF8)
                                                        : "application/octet-stream";

                        if (metadata.ContainsKey("name"))
                        {
                            var name = metadata["name"].GetString(Encoding.UTF8);
                            context.Response.Headers.Add("Content-Disposition", new[] { $"attachment; filename=\"{name}\"" });
                        }

                        await fileStream.CopyToAsync(context.Response.Body, 81920, context.Request.CallCancelled);
                        return;
                    }
                }

                switch (context.Request.Uri.LocalPath)
                {
                case "/":
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync(File.ReadAllText("../../index.html"), context.Request.CallCancelled);
                    break;

                case "/tus.js":
                    context.Response.ContentType = "application/js";
                    await context.Response.WriteAsync(File.ReadAllText("../../tus.js"), context.Request.CallCancelled);
                    break;

                default:
                    context.Response.StatusCode = 404;
                    break;
                }
            });

            // Setup cleanup job to remove incomplete expired files.
            // This is just a simple example. In production one would use a cronjob/webjob and poll an endpoint that runs RemoveExpiredFilesAsync.
            var onAppDisposingToken = new OwinContext(app.Properties).Get <CancellationToken>("host.OnAppDisposing");

            Task.Run(async() =>
            {
                while (!onAppDisposingToken.IsCancellationRequested)
                {
                    Console.WriteLine("Running cleanup job...");
                    var numberOfRemovedFiles = await _tusDiskStore.RemoveExpiredFilesAsync(onAppDisposingToken);
                    Console.WriteLine(
                        $"Removed {numberOfRemovedFiles} expired files. Scheduled to run again in {_absoluteExpiration.Timeout.TotalMilliseconds} ms");
                    await Task.Delay(_absoluteExpiration.Timeout, onAppDisposingToken);
                }
            }, onAppDisposingToken);
        }
        protected virtual System.Web.Cors.CorsPolicy Allow(string origin)
        {
            var p = new System.Web.Cors.CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
            };

            p.Origins.Add(origin);
            return p;
        }
Exemplo n.º 14
0
        /// <summary>Configures the authentication.
        /// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864</summary>
        /// <param name="app">The app.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            // Changing this setting requires a website restart
            var corsOrigin = BootStrapper.GetApplicationSetting("Cors_Origin", string.Empty);
            if (!corsOrigin.IsBlank())
            {
                var policy = new CorsPolicy
                {
                    AllowAnyHeader = true, 
                    AllowAnyMethod = true, 
                    AllowAnyOrigin = corsOrigin.Equals("*"), 
                    SupportsCredentials = true
                };
                if (!policy.AllowAnyOrigin)
                {
                    corsOrigin.Split(',').ForEach(origin => policy.Origins.Add(origin.Trim()));
                }

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

            app.CreatePerOwinContext(IdentityDbContext.Create);
            app.CreatePerOwinContext<IdentityUserManager>(IdentityUserManager.Create);
            app.CreatePerOwinContext<IdentitySignInManager>(IdentitySignInManager.Create);

            app.UseKentorOwinCookieSaver();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = SecurityOptions.IdentityServerOptions.IssuerUri,
                RequiredScopes = new[] { SecurityOptions.Scope },
                NameClaimType = Constants.ClaimTypes.PreferredUserName,
                RoleClaimType = Constants.ClaimTypes.Role
            });


            app.UseCookieAuthentication(SecurityOptions.CookieOptions);

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Map("/identity", identityApp => { identityApp.UseIdentityServer(SecurityOptions.IdentityServerOptions); });

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            // app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            // app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }