/// <summary>
 /// Create an instance of the options initialized with the default values
 /// </summary>
 public CookieAuthenticationOptions()
 {
     ExpireTimeSpan     = TimeSpan.FromDays(14);
     ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
     SlidingExpiration  = true;
     Events             = new CookieAuthenticationEvents();
 }
        public static void DisableRedirectForPath(
            this CookieAuthenticationEvents events,
            Expression <Func <CookieAuthenticationEvents,
                              Func <RedirectContext <CookieAuthenticationOptions>, Task> > > expr,
            string path, int statuscode)
        {
            string propertyName = ((MemberExpression)expr.Body).Member.Name;
            var    oldHandler   = expr.Compile().Invoke(events);

            Func <RedirectContext <CookieAuthenticationOptions>, Task> newHandler
                = context => {
                if (context.Request.Path.StartsWithSegments(path))
                {
                    context.Response.StatusCode = statuscode;
                }
                else
                {
                    oldHandler(context);
                }
                return(Task.CompletedTask);
                };

            typeof(CookieAuthenticationEvents).GetProperty(propertyName)
            .SetValue(events, newHandler);
        }
        public static CookieAuthenticationOptions SetupAppCookie(
            this IApplicationBuilder app,
           SiteAuthCookieValidator siteValidator,
           string scheme,
           bool useRelatedSitesMode,
           SiteContext tenant,
           CookieSecurePolicy cookieSecure = CookieSecurePolicy.SameAsRequest
           )
        {
            var cookieEvents = new CookieAuthenticationEvents();
            var options = new CookieAuthenticationOptions();
            if (useRelatedSitesMode)
            {
                options.AuthenticationScheme = scheme;
                options.CookieName = scheme;
                options.CookiePath = "/";
            }
            else
            {
                //options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}";
                options.AuthenticationScheme = scheme;
                options.CookieName = $"{scheme}-{tenant.SiteFolderName}";
                options.CookiePath = "/" + tenant.SiteFolderName;
                cookieEvents.OnValidatePrincipal = siteValidator.ValidatePrincipal;
            }

            var tenantPathBase = string.IsNullOrEmpty(tenant.SiteFolderName)
                ? PathString.Empty
                : new PathString("/" + tenant.SiteFolderName);

            options.LoginPath = tenantPathBase + "/account/login";
            options.LogoutPath = tenantPathBase + "/account/logoff";
            options.AccessDeniedPath = tenantPathBase + "/account/accessdenied";

            options.Events = cookieEvents;

            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = false;

            options.CookieSecure = cookieSecure;

            return options;
        }
Exemple #4
0
        private CookieAuthenticationOptions SetupAppCookie(
            CookieAuthenticationEvents cookieEvents,
            cloudscribe.Core.Identity.SiteAuthCookieValidator siteValidator,
            string scheme, 
            bool useRelatedSitesMode,
            cloudscribe.Core.Models.SiteSettings tenant
            )
        {
            var options = new CookieAuthenticationOptions();
            if(useRelatedSitesMode)
            {
                options.AuthenticationScheme = scheme;
                options.CookieName = scheme;
                options.CookiePath = "/";
            }
            else
            {
                options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}";
                options.CookieName = $"{scheme}-{tenant.SiteFolderName}";
                options.CookiePath = "/" + tenant.SiteFolderName;
                cookieEvents.OnValidatePrincipal = siteValidator.ValidatePrincipal;
            }
            
            var tenantPathBase = string.IsNullOrEmpty(tenant.SiteFolderName)
                ? PathString.Empty
                : new PathString("/" + tenant.SiteFolderName);

            options.LoginPath = tenantPathBase + "/account/login";
            options.LogoutPath = tenantPathBase + "/account/logoff";
            
            options.Events = cookieEvents;

            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
           

            return options;
        }
Exemple #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // you can add things to this method signature and they will be injected as long as they were registered during 
        // ConfigureServices
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<cloudscribe.Core.Models.MultiTenantOptions> multiTenantOptionsAccessor,
            IServiceProvider serviceProvider,
            IOptions<RequestLocalizationOptions> localizationOptionsAccessor
            )
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            var storage = Configuration["DevOptions:DbPlatform"];
            if(storage != "NoDb")
            {   
                ConfigureLogging(loggerFactory, serviceProvider);
            }
            
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //}
            
            app.UseStaticFiles();

            // custom 404 and error page - this preserves the status code (ie 404)
            app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

            app.UseSession();
            
            app.UseRequestLocalization(localizationOptionsAccessor.Value);

            app.UseMultitenancy<cloudscribe.Core.Models.SiteSettings>();

            //app.UseTenantContainers<SiteSettings>();
            var multiTenantOptions = multiTenantOptionsAccessor.Value;

            app.UsePerTenant<cloudscribe.Core.Models.SiteSettings>((ctx, builder) =>
            {
                var tenant = ctx.Tenant;

                var shouldUseFolder = !multiTenantOptions.UseRelatedSitesMode
                                        && multiTenantOptions.Mode == cloudscribe.Core.Models.MultiTenantMode.FolderName
                                        && tenant.SiteFolderName.Length > 0;
                
                var externalCookieOptions = SetupOtherCookies(
                    cloudscribe.Core.Identity.AuthenticationScheme.External,
                    multiTenantOptions.UseRelatedSitesMode,
                    tenant);
                builder.UseCookieAuthentication(externalCookieOptions);

                var twoFactorRememberMeCookieOptions = SetupOtherCookies(
                    cloudscribe.Core.Identity.AuthenticationScheme.TwoFactorRememberMe,
                    multiTenantOptions.UseRelatedSitesMode,
                    tenant);
                builder.UseCookieAuthentication(twoFactorRememberMeCookieOptions);

                var twoFactorUserIdCookie = SetupOtherCookies(
                    cloudscribe.Core.Identity.AuthenticationScheme.TwoFactorUserId,
                    multiTenantOptions.UseRelatedSitesMode,
                    tenant);
                builder.UseCookieAuthentication(twoFactorUserIdCookie);

                var cookieEvents = new CookieAuthenticationEvents();
                var logger = loggerFactory.CreateLogger<cloudscribe.Core.Identity.SiteAuthCookieValidator>();
                var cookieValidator = new cloudscribe.Core.Identity.SiteAuthCookieValidator(logger);
                var appCookieOptions = SetupAppCookie(
                    cookieEvents,
                    cookieValidator,
                    cloudscribe.Core.Identity.AuthenticationScheme.Application,
                    multiTenantOptions.UseRelatedSitesMode,
                    tenant
                    );
                builder.UseCookieAuthentication(appCookieOptions);

                //builder.UseForwardedHeaders();
                // known issue here is if a site is updated to populate the
                // social auth keys, it currently requires a restart so that the middleware gets registered
                // in order for it to work or for the social auth buttons to appear 
                builder.UseSocialAuth(ctx.Tenant, externalCookieOptions, shouldUseFolder);
                
            });

            

            UseMvc(app, multiTenantOptions.Mode == cloudscribe.Core.Models.MultiTenantMode.FolderName);
            
            switch (storage)
            {
                case "NoDb":
                    CoreNoDbStartup.InitializeDataAsync(app.ApplicationServices).Wait();
                    break;

                case "ef":
                default:
                    // this creates ensures the database is created and initial data
                    CoreEFStartup.InitializeDatabaseAsync(app.ApplicationServices).Wait();

                    // this one is only needed if using cloudscribe Logging with EF as the logging storage
                    LoggingEFStartup.InitializeDatabaseAsync(app.ApplicationServices).Wait();

                    break;
            }

           
        }