public virtual void OnAppStartup()
        {
            TemplateServiceConfiguration config = new TemplateServiceConfiguration();

            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            config.Debug                = activeAppEnvironment.DebugMode;
            config.Language             = Language.CSharp;
            config.EncodedStringFactory = new NullCompatibleEncodedStringFactory();

            IRazorEngineService service = RazorEngineService.Create(config);

            Engine.Razor = service;

            string defaultPageTemplateFilePath = PathProvider.StaticFileMapPath(activeAppEnvironment.GetConfig("DefaultPageTemplatePath", "defaultPageTemplate.cshtml"));

            if (File.Exists(defaultPageTemplateFilePath))
            {
                string defaultPageTemplateContents = File.ReadAllText(defaultPageTemplateFilePath);

                Engine.Razor.Compile(name: "defaultPageTemplate", modelType: typeof(IDependencyResolver),
                                     templateSource: new LoadedTemplateSource(defaultPageTemplateContents, defaultPageTemplateFilePath));
            }

            string ssoPageTemplateFilePath = PathProvider.StaticFileMapPath(activeAppEnvironment.GetConfig("SsoPageTemplatePath", "ssoPageTemplate.cshtml"));

            if (File.Exists(ssoPageTemplateFilePath))
            {
                string ssoPageTemplateContents = File.ReadAllText(ssoPageTemplateFilePath);

                Engine.Razor.Compile(name: "ssoPageTemplate", modelType: typeof(IDependencyResolver),
                                     templateSource: new LoadedTemplateSource(ssoPageTemplateContents, ssoPageTemplateFilePath));
            }
        }
        public virtual void OnAppStartup()
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            string jobSchedulerDbConnectionString = activeAppEnvironment.GetConfig <string>("JobSchedulerDbConnectionString");

            SqlServerStorage storage = new SqlServerStorage(jobSchedulerDbConnectionString, new SqlServerStorageOptions
            {
                PrepareSchemaIfNecessary  = false,
                TransactionIsolationLevel = IsolationLevel.ReadCommitted,
                SchemaName = "Jobs"
            });

            if (activeAppEnvironment.DebugMode == false)
            {
                string signalRAzureServiceBusConnectionString = activeAppEnvironment.GetConfig <string>("JobSchedulerAzureServiceBusConnectionString");

                storage.UseServiceBusQueues(signalRAzureServiceBusConnectionString);
            }

            GlobalConfiguration.Configuration.UseStorage(storage);
            GlobalConfiguration.Configuration.UseAutofacActivator(_lifetimeScope);
            GlobalConfiguration.Configuration.UseLogProvider(_logProvider);

            _backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
            {
                Activator = _jobActivator
            }, storage);
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            owinApp.Map("/core", coreApp =>
            {
                LogProvider.SetCurrentLogProvider(_dependencyManager.Resolve <ILogProvider>());

                AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

                IdentityServerServiceFactory factory = new IdentityServerServiceFactory()
                                                       .UseInMemoryClients(_dependencyManager.Resolve <IClientProvider>().GetClients().ToArray())
                                                       .UseInMemoryScopes(_scopesProvider.GetScopes());

                factory.UserService =
                    new Registration <IUserService>(_dependencyManager.Resolve <IUserService>());

                factory.ViewService = new Registration <IViewService>(_dependencyManager.Resolve <IViewService>());

                bool requireSslConfigValue = activeAppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false);

                string identityServerSiteName = activeAppEnvironment.GetConfig("IdentityServerSiteName", "Identity Server");

                IdentityServerOptions identityServerOptions = new IdentityServerOptions
                {
                    SiteName           = identityServerSiteName,
                    SigningCertificate = _certificateProvider.GetSingleSignOnCertificate(),
                    Factory            = factory,
                    RequireSsl         = requireSslConfigValue,
                    EnableWelcomePage  = activeAppEnvironment.DebugMode == true,
                    CspOptions         = new CspOptions
                    {
                        // Content security policy
                        Enabled = false
                    },
                    Endpoints = new EndpointOptions
                    {
                        EnableAccessTokenValidationEndpoint   = true,
                        EnableAuthorizeEndpoint               = true,
                        EnableCheckSessionEndpoint            = true,
                        EnableClientPermissionsEndpoint       = true,
                        EnableCspReportEndpoint               = true,
                        EnableDiscoveryEndpoint               = true,
                        EnableEndSessionEndpoint              = true,
                        EnableIdentityTokenValidationEndpoint = true,
                        EnableIntrospectionEndpoint           = true,
                        EnableTokenEndpoint           = true,
                        EnableTokenRevocationEndpoint = true,
                        EnableUserInfoEndpoint        = true
                    }
                };

                coreApp.UseIdentityServer(identityServerOptions);
            });
        }
        public virtual void Configure(HubConfiguration signalRConfig)
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            string sqlServerConnectionString = activeAppEnvironment.GetConfig <string>("SignalRSqlServerConnectionString");

            signalRConfig.Resolver.UseSqlServer(new SqlScaleoutConfiguration(sqlServerConnectionString)
            {
                TableCount = activeAppEnvironment.GetConfig("SignalRSqlServerTableCount", 3)
            });
        }
Exemplo n.º 5
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            if (_baseRedirectUri == null)
            {
                _baseRedirectUri = $"{activEnvironment.Security.SSOServerUrl}/connect/authorize?scope={string.Join(" ", activEnvironment.Security.Scopes)}&client_id={activEnvironment.Security.ClientName}&redirect_uri={activEnvironment.GetConfig("ClientHostBaseUri", context.Request.Host.Value)}{activEnvironment.GetConfig("ClientHostVirtualPath", "/")}SignIn&response_type=id_token token";
            }

            string pathname = activEnvironment.GetConfig("ClientHostVirtualPath", "/") + (context.Request.Path.HasValue ? context.Request.Path.Value.Substring(1) : string.Empty);

            string state = $@"{{""pathname"":""{pathname}""}}";

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            string redirectUrl = $"{_baseRedirectUri}&state={state}&nonce={nonce}";

            context.Response.Redirect(redirectUrl);

            return(Task.CompletedTask);
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            owinApp.Map("/SignOut",
                        innerApp =>
            {
                if (_activeAppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false))
                {
                    innerApp.UseHsts(config => config.IncludeSubdomains().MaxAge(days: 30));
                }

                innerApp.UseXfo(xFrameOptions => { xFrameOptions.SameOrigin(); });

                innerApp.UseXContentTypeOptions();

                innerApp.UseXDownloadOptions();

                innerApp.UseXXssProtection(xssProtectionOptions => { xssProtectionOptions.EnabledWithBlockMode(); });

                innerApp.Use <OwinNoCacheResponseMiddleware>();

                innerApp.Use <SignOutPageMiddleware>();
            });
        }
Exemplo n.º 7
0
        public virtual void OnAppStartup()
        {
            string jobSchedulerDbConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerDbConnectionString");

            SqlServerStorage storage = new SqlServerStorage(jobSchedulerDbConnectionString, new SqlServerStorageOptions
            {
                PrepareSchemaIfNecessary  = false,
                TransactionIsolationLevel = IsolationLevel.ReadCommitted,
                SchemaName = "Jobs"
            });

            if (AppEnvironment.HasConfig("JobSchedulerAzureServiceBusConnectionString"))
            {
                string signalRAzureServiceBusConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerAzureServiceBusConnectionString");

                storage.UseServiceBusQueues(signalRAzureServiceBusConnectionString);
            }

            JobStorage.Current = storage;
            GlobalConfiguration.Configuration.UseStorage(storage);
            GlobalConfiguration.Configuration.UseAutofacActivator(_lifetimeScope);
            GlobalConfiguration.Configuration.UseLogProvider(LogProvider);

            BackgroundJobServerOptions options = new BackgroundJobServerOptions
            {
                Activator = JobActivator
            };

            foreach (IHangfireOptionsCustomizer customizer in Customizers)
            {
                customizer.Customize(GlobalConfiguration.Configuration, options, storage);
            }

            _backgroundJobServer = new BackgroundJobServer(options, storage);
        }
        public virtual X509Certificate2 GetSingleSignOnServerCertificate()
        {
            if (_certificate == null)
            {
                string password = AppEnvironment
                                  .GetConfig <string>(AppEnvironment.KeyValues.IdentityCertificatePassword) ?? throw new InvalidOperationException($"{nameof(AppEnvironment.KeyValues.IdentityCertificatePassword)} is null.");

                byte[] pfxRaw = File.ReadAllBytes(PathProvider.MapPath(AppEnvironment.GetConfig(AppEnvironment.KeyValues.IdentityServerCertificatePath, AppEnvironment.KeyValues.IdentityServerCertificatePathDefaultValue) !));

                try
                {
                    _certificate = new X509Certificate2(pfxRaw, password);
                }
                catch
                {
                    _certificate = new X509Certificate2(pfxRaw, password, X509KeyStorageFlags.UserKeySet);
                }

                using X509Chain chain = new X509Chain();
                bool isValid = chain.Build(_certificate);
                if (!isValid && chain.ChainStatus.Any(s => s.Status == X509ChainStatusFlags.NotTimeValid))
                {
                    throw new InvalidOperationException($"A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file.");
                }
            }

            return(_certificate);
        }
        public virtual Task SaveLogAsync(LogEntry logEntry)
        {
            if (logEntry == null)
            {
                throw new ArgumentNullException(nameof(logEntry));
            }

            EventLog appLog = new EventLog("Application")
            {
                Source = _activeAppEnvironment.AppInfo.Name
            };

            EventLogEntryType eventLogsSeverity;

            if (logEntry.Severity == "Warning")
            {
                eventLogsSeverity = EventLogEntryType.Warning;
            }
            else if (logEntry.Severity == "Information")
            {
                eventLogsSeverity = EventLogEntryType.Information;
            }
            else
            {
                eventLogsSeverity = EventLogEntryType.Error;
            }

            string logContents = _contentFormatter.Serialize(logEntry);

            if (logContents.Length >= 30000)
            {
                logContents = logContents.Substring(0, 29999);
            }

            if (_activeAppEnvironment.Configs.Any(c => string.Equals(c.Key, "EventLogId", StringComparison.CurrentCultureIgnoreCase)))
            {
                appLog.WriteEntry(logContents, eventLogsSeverity, Convert.ToInt32(_activeAppEnvironment.GetConfig <long>("EventLogId")));
            }
            else
            {
                appLog.WriteEntry(logContents, eventLogsSeverity);
            }

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 10
0
        public virtual void Configure(HubConfiguration signalRConfig)
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            string signalRAzureServiceBusConnectionString =
                activeAppEnvironment.GetConfig <string>("SignalRAzureServiceBusConnectionString");

            signalRConfig.Resolver.UseServiceBus(signalRAzureServiceBusConnectionString, "SignalR");
        }
        public virtual void OnAppStartup()
        {
            string templateFilePath = _pathProvider.StaticFileMapPath(_activeAppEnvironment.GetConfig("DefaultPageTemplatePath", "defaultPageTemplate.cshtml"));

            string template = File.ReadAllText(templateFilePath);

            Engine.Razor.Compile(name: "defaultPageTemplate", modelType: typeof(IDependencyResolver),
                                 templateSource: new LoadedTemplateSource(template, templateFilePath));
        }
Exemplo n.º 12
0
        public virtual IEnumerable <Client> GetClients()
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            return(new[]
            {
                new Client
                {
                    ClientName = "BitChangeSetManager",
                    Enabled = true,
                    ClientId = "BitChangeSetManager",
                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret".Sha512())
                    },
                    Flow = Flows.Implicit,
                    AllowedScopes = new List <string>
                    {
                        Constants.StandardScopes.OpenId,
                        Constants.StandardScopes.Profile,
                        "user_info"
                    },
                    ClientUri = "https://github.com/bit-foundation/bit-framework/",
                    RequireConsent = false,
                    RedirectUris = new List <string>
                    {
                        $@"{activeAppEnvironment.GetConfig<string>("ClientHostBaseUri")}{activeAppEnvironment.GetConfig<string>("ClientHostVirtualPath")}SignIn"
                    },
                    PostLogoutRedirectUris = new List <string>
                    {
                        $@"{activeAppEnvironment.GetConfig<string>("ClientHostBaseUri")}{activeAppEnvironment.GetConfig<string>("ClientHostVirtualPath")}SignOut"
                    },
                    AllowAccessToAllScopes = true,
                    AlwaysSendClientClaims = true,
                    IncludeJwtId = true,
                    IdentityTokenLifetime = 86400 /*1 Day*/,
                    AccessTokenLifetime = 86400 /*1 Day*/,
                    AuthorizationCodeLifetime = 86400 /*1 Day*/,
                    AccessTokenType = AccessTokenType.Jwt,
                    AllowAccessToAllCustomGrantTypes = true
                }
            });
        }
Exemplo n.º 13
0
        public virtual void ConfiguerExternalIdentityProvider(IAppBuilder owinApp, string signInType)
        {
            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            if (activeAppEnvironment.HasConfig("FacebookClientId") && activeAppEnvironment.HasConfig("FacebookSecret"))
            {
                string facebookClientId = activeAppEnvironment.GetConfig <string>("FacebookClientId");
                string facebookSecret   = activeAppEnvironment.GetConfig <string>("FacebookSecret");

                FacebookAuthenticationOptions facebookAuthenticationOptions = new FacebookAuthenticationOptions
                {
                    AuthenticationType         = "Facebook",
                    SignInAsAuthenticationType = signInType,
                    AppId     = facebookClientId,
                    AppSecret = facebookSecret,
                    Provider  = new FacebookAuthenticationProvider
                    {
                        OnAuthenticated = async context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken));

                            foreach (KeyValuePair <string, JToken> claim in context.User)
                            {
                                string claimType  = $"{claim.Key}";
                                string claimValue = claim.Value.ToString();

                                if (!context.Identity.HasClaim(claimType, claimValue))
                                {
                                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                                }
                            }
                        }
                    }
                };

                facebookAuthenticationOptions.Fields.Add("email");
                facebookAuthenticationOptions.Fields.Add("first_name");
                facebookAuthenticationOptions.Fields.Add("last_name");

                owinApp.UseFacebookAuthentication(facebookAuthenticationOptions);
            }
        }
 public virtual SSOPageModel GetSSOPageModel()
 {
     return(new SSOPageModel
     {
         AppTitle = _activeAppEnvironment
                    .Cultures
                    .Single(c => c.Name == _activeAppEnvironment.AppInfo.DefaultCulture)
                    .Values
                    .Single(v => v.Name == "AppTitle").Title,
         AppName = _activeAppEnvironment.AppInfo.Name,
         AppVersion = _activeAppEnvironment.AppInfo.Version,
         Culture = _activeAppEnvironment.AppInfo.DefaultCulture,
         DebugMode = _activeAppEnvironment.DebugMode,
         DesiredTimeZoneValue = _activeAppEnvironment.AppInfo.DefaultTimeZone,
         Theme = _activeAppEnvironment.AppInfo.DefaultTheme,
         EnvironmentConfigsJSON = _contentFormatter.Serialize(_activeAppEnvironment
                                                              .Configs.Where(c => c.AccessibleInClientSide == true)
                                                              .Select(c => new { value = c.Value, key = c.Key })),
         BaseHref = _activeAppEnvironment.GetConfig("ClientHostVirtualPath", "/")
     });
 }
        public virtual X509Certificate2 GetSingleSignOnCertificate()
        {
            if (_certificate == null)
            {
                string password = AppEnvironment
                                  .GetConfig <string>(AppEnvironment.KeyValues.IdentityCertificatePassword) ?? throw new InvalidOperationException($"{nameof(AppEnvironment.KeyValues.IdentityCertificatePassword)} is null.");

                _certificate = new X509Certificate2(File.ReadAllBytes(PathProvider.MapPath(AppEnvironment.GetConfig(AppEnvironment.KeyValues.IdentityServerCertificatePath, AppEnvironment.KeyValues.IdentityServerCertificatePathDefaultValue) !)),
                                                    password);
            }

            return(_certificate);
        }
Exemplo n.º 16
0
        public virtual void ConfiguerExternalIdentityProvider(IAppBuilder owinApp, string signInType)
        {
            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            if (activeAppEnvironment.HasConfig("TwitterClientId") && activeAppEnvironment.HasConfig("TwitterSecret"))
            {
                string twitterClientId = activeAppEnvironment.GetConfig <string>("TwitterClientId");
                string twitterSecret   = activeAppEnvironment.GetConfig <string>("TwitterSecret");

                TwitterAuthenticationOptions twitterAuthenticationOptions = new TwitterAuthenticationOptions
                {
                    AuthenticationType         = "Twitter",
                    SignInAsAuthenticationType = signInType,
                    ConsumerKey    = twitterClientId,
                    ConsumerSecret = twitterSecret,
                    Provider       = new TwitterAuthenticationProvider
                    {
                        OnAuthenticated = async context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken));
                            context.Identity.AddClaim(new System.Security.Claims.Claim("access_token_secret", context.AccessTokenSecret));

                            foreach (System.Security.Claims.Claim claim in context.Identity.Claims)
                            {
                                string claimType  = $"{claim.Type}";
                                string claimValue = claim.Value;

                                if (!context.Identity.HasClaim(claimType, claimValue))
                                {
                                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter"));
                                }
                            }
                        }
                    }
                };

                owinApp.UseTwitterAuthentication(twitterAuthenticationOptions);
            }
        }
        public virtual X509Certificate2 GetSingleSignOnCertificate()
        {
            if (_certificate == null)
            {
                string password = AppEnvironment
                                  .GetConfig <string>("IdentityCertificatePassword");

                _certificate = new X509Certificate2(File.ReadAllBytes(PathProvider.MapPath(AppEnvironment.GetConfig("IdentityServerCertificatePath", "IdentityServerCertificate.pfx"))),
                                                    password);
            }

            return(_certificate);
        }
Exemplo n.º 18
0
        public virtual void ConfiguerExternalIdentityProvider(IAppBuilder owinApp, string signInType)
        {
            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            if (activeAppEnvironment.HasConfig("MicrosoftClientId") && activeAppEnvironment.HasConfig("MicrosoftSecret"))
            {
                string microsoftClientId = activeAppEnvironment.GetConfig <string>("MicrosoftClientId");
                string microsoftSecret   = activeAppEnvironment.GetConfig <string>("MicrosoftSecret");

                MicrosoftAccountAuthenticationOptions microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions
                {
                    AuthenticationType         = "Microsoft",
                    SignInAsAuthenticationType = signInType,
                    ClientId     = microsoftClientId,
                    ClientSecret = microsoftSecret,
                    Provider     = new MicrosoftAccountAuthenticationProvider
                    {
                        OnAuthenticated = async context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken));

                            foreach (KeyValuePair <string, JToken> claim in context.User)
                            {
                                string claimType  = $"{claim.Key}";
                                string claimValue = claim.Value.ToString();

                                if (!context.Identity.HasClaim(claimType, claimValue))
                                {
                                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                                }
                            }
                        }
                    }
                };

                owinApp.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions);
            }
        }
Exemplo n.º 19
0
        public virtual async Task <DefaultPageModel> GetDefaultPageModelAsync(CancellationToken cancellationToken)
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            DefaultPageModel defaultPageModel = new DefaultPageModel
            {
                AppVersion = activeAppEnvironment.AppInfo.Version,
                DebugMode  = activeAppEnvironment.DebugMode,
                AppName    = activeAppEnvironment.AppInfo.Name
            };

            UserSetting userSetting = await _usersSettingsProvider.GetCurrentUserSettingAsync(cancellationToken);

            string theme = userSetting?.Theme ?? activeAppEnvironment.AppInfo.DefaultTheme;

            string culture = userSetting?.Culture ?? activeAppEnvironment.AppInfo.DefaultCulture;

            string desiredTimeZone = userSetting?.DesiredTimeZone ??
                                     activeAppEnvironment.AppInfo.DefaultTimeZone;

            string desiredTimeZoneValue = null;

            if (culture == null || string.Equals(culture, "Auto", StringComparison.OrdinalIgnoreCase))
            {
                culture = "EnUs";
            }

            if (desiredTimeZone != null &&
                !string.Equals(desiredTimeZone, "Auto", StringComparison.CurrentCulture))
            {
                desiredTimeZoneValue = desiredTimeZone;
            }

            string appTitle = activeAppEnvironment.Cultures.Any() ? activeAppEnvironment.Cultures
                              .Single(c => c.Name == culture).Values.Single(v =>
                                                                            string.Equals(v.Name, "AppTitle", StringComparison.OrdinalIgnoreCase)).Title : string.Empty;

            defaultPageModel.AppTitle             = appTitle;
            defaultPageModel.Culture              = culture;
            defaultPageModel.DesiredTimeZoneValue = desiredTimeZoneValue;
            defaultPageModel.Theme = theme;

            defaultPageModel.EnvironmentConfigsJSON = _contentFormatter.Serialize(activeAppEnvironment
                                                                                  .Configs.Where(c => c.AccessibleInClientSide == true)
                                                                                  .Select(c => new { value = c.Value, key = c.Key }));

            defaultPageModel.BaseHref = activeAppEnvironment.GetConfig("ClientHostVirtualPath", "/");

            return(defaultPageModel);
        }
        public virtual X509Certificate2 GetSingleSignOnCertificate()
        {
            if (_certificate == null)
            {
                AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

                string password = activeAppEnvironment
                                  .GetConfig <string>("IdentityCertificatePassword");

                _certificate = new X509Certificate2(File.ReadAllBytes(_pathProvider.MapPath(activeAppEnvironment.GetConfig <string>("IdentityServerCertificatePath"))),
                                                    password);
            }

            return(_certificate);
        }
Exemplo n.º 21
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string defaultPath = activEnvironment.GetConfig("ClientHostVirtualPath", "/");

            string signInPage = $@"
<html>
    <head>
        <title>Signing in... Please wait</title>
        <script type='application/javascript'>
            var parts = location.hash.replace('#','').split('&');
            var expireTimeInSeconds = Number(parts[3].split('=')[1]);
            var now = new Date();
            var time = now.getTime();
            var expireTime = time + (expireTimeInSeconds * 1000);
            now.setTime(expireTime);
            var nowAsGMTString = now.toGMTString();
            for (var i = 0; i < parts.length; i++) {{
                var partStr = parts[i];
                var keyValue = partStr.split('=');
                var key = keyValue[0];
                var value = keyValue[1];
                if (key == 'access_token' || key == 'token_type'){{
                    document.cookie = partStr + ';expires=' + nowAsGMTString + ';path={defaultPath}';
                }}
                localStorage[key] = value;
            }}
            localStorage['login_date'] = new Date();
            var state = JSON.parse(decodeURIComponent(localStorage.state.replace(/\+/g, ' ')));
            localStorage['state'] = JSON.stringify(state);
            location = state.pathname || '{defaultPath}';
        </script>
    </head>
    <body>
        <h1>Signing in... Please wait</h1>
    </body>
</html>
";

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(signInPage);
        }
Exemplo n.º 22
0
        public virtual async Task <string> GetSsoPageAsync(CancellationToken cancellationToken)
        {
            if (_result == null)
            {
                string templateFilePath = _pathProvider.MapPath(_activeAppEnvironment.GetConfig <string>("SsoPageTemplatePath"));

                string template = File.ReadAllText(templateFilePath);

                Engine.Razor.Compile(name: "ssoPageTemplate", modelType: typeof(IDependencyManager),
                                     templateSource: new LoadedTemplateSource(template, templateFilePath));

                _result = Engine.Razor.Run("ssoPageTemplate", typeof(IDependencyManager), _dependencyManager);
            }

            return(_result);
        }
        public virtual void OnAppStartup()
        {
            string jobSchedulerDbConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerDbConnectionString");

            SqlServerStorage storage = new SqlServerStorage(jobSchedulerDbConnectionString, new SqlServerStorageOptions
            {
                PrepareSchemaIfNecessary     = false,
                UseRecommendedIsolationLevel = true,
                SchemaName                 = "HangFire",
                CommandBatchMaxTimeout     = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                QueuePollInterval          = TimeSpan.Zero,
                UsePageLocksOnDequeue      = true,
                DisableGlobalLocks         = true
            }); // https://docs.hangfire.io/en/latest/configuration/using-sql-server.html#configuration

            if (AppEnvironment.HasConfig("JobSchedulerAzureServiceBusConnectionString"))
            {
                string signalRAzureServiceBusConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerAzureServiceBusConnectionString");

                storage.UseServiceBusQueues(signalRAzureServiceBusConnectionString);
            }

            JobStorage.Current = storage;
            GlobalConfiguration.Configuration.UseStorage(storage);
            GlobalConfiguration.Configuration.UseAutofacActivator(_lifetimeScope);
            GlobalConfiguration.Configuration.UseLogProvider(LogProvider);

            if (GlobalJobFilters.Filters.Any(f => f.Instance is AutomaticRetryAttribute))
            {
                GlobalConfiguration.Configuration.UseFilter(new DefaultAutomaticRetryAttribute {
                });
                GlobalJobFilters.Filters.Remove(GlobalJobFilters.Filters.ExtendedSingle("Finding automatic retry job filter attribute to remove it from global job filters", f => f.Instance is AutomaticRetryAttribute).Instance);
            }

            BackgroundJobServerOptions options = new BackgroundJobServerOptions
            {
                Activator = JobActivator
            };

            foreach (IHangfireOptionsCustomizer customizer in Customizers)
            {
                customizer.Customize(GlobalConfiguration.Configuration, options, storage);
            }

            _backgroundJobServer = new BackgroundJobServer(options, storage);
        }
Exemplo n.º 24
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

            AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            string defaultPath = activEnvironment.GetConfig("ClientHostVirtualPath", "/");

            string singOutPage = $@"
<html>
    <head>
        <title>Signing out... Please wait</title>
        <script type='application/javascript'>
            localStorage.removeItem('access_token');
            localStorage.removeItem('expires_in');
            localStorage.removeItem('id_token');
            localStorage.removeItem('login_date');
            localStorage.removeItem('scope');
            localStorage.removeItem('session_state');
            localStorage.removeItem('state');
            localStorage.removeItem('token_type');
            var cookies = document.cookie.split('; ');
            for (var i = 0; i < cookies.length; i++)
            {{
                var cookie = cookies[i];
                var eqPos = cookie.indexOf('=');
                var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
                if(name == 'access_token' || name == 'token_type')
                    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT';
            }}
            location = '{defaultPath}';
        </script>
    </head>
    <body>
        <h1>Signing out... Please wait</h1>
    </body>
</html>
";

            context.Response.ContentType = "text/html; charset=utf-8";

            await context.Response.WriteAsync(singOutPage);
        }
Exemplo n.º 25
0
        public async Task <IEnumerable <CityDto> > GetAll(CancellationToken cancellationToken)
        {
            ODataSqlQuery odataSqlQuery = ODataSqlBuilder.BuildSqlQuery(GetODataQueryOptions(), tableName: "bit.Cities");

            string connectionString = AppEnvironment.GetConfig <string>("BitChangeSetManagerDbConnectionString");

            DbConnection dbConnection = await DbConnectionProvider.GetDbConnectionAsync(connectionString, true, cancellationToken);

            DbTransaction dbTransaction = DbConnectionProvider.GetDbTransaction(connectionString);

            IEnumerable <CityDto> cities = await dbConnection.QueryAsync <CityDto>(odataSqlQuery.SelectQuery, odataSqlQuery.Parts.Parameters, transaction : dbTransaction);

            long total = odataSqlQuery.Parts.GetTotalCountFromDb == false?cities.LongCount() : ((await dbConnection.ExecuteScalarAsync <long?>(odataSqlQuery.SelectTotalCountQuery, odataSqlQuery.Parts.Parameters, transaction: dbTransaction)) ?? 0);

            Request.Properties["System.Web.OData.TotalCountFunc"] = new Func <long>(() => total);

            return(cities);
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            if (_activeAppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false))
            {
                owinApp.UseHsts(TimeSpan.FromDays(1));
            }

            owinApp.UseXContentTypeOptions();

            owinApp.UseXDownloadOptions();

            owinApp.UseXXssProtection(xssProtectionOptions => { xssProtectionOptions.EnabledWithBlockMode(); });

            owinApp.Use <OwinNoCacheResponseMiddleware>();

            owinApp.Use <DefaultPageMiddleware>();
        }
Exemplo n.º 27
0
        public virtual async Task <Stream> Login(LoginViewModel model, SignInMessage message)
        {
            JsonSerializerSettings jsonSerSettings = DefaultJsonContentFormatter.SerializeSettings();

            jsonSerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            if (model.Custom == null && message.ReturnUrl != null)
            {
                try
                {
                    dynamic custom = model.Custom = UrlStateProvider.GetState(new Uri(message.ReturnUrl));

                    string signInType = null;

                    try
                    {
                        signInType = custom.SignInType;
                    }
                    catch { }

                    if (signInType != null && model.ExternalProviders.Any(extProvider => extProvider.Type == signInType))
                    {
                        string redirectUri = model.ExternalProviders.Single(extProvider => extProvider.Type == signInType).Href;

                        return(await ReturnHtmlAsync(model, $@"<!DOCTYPE html>
                            <html>
                                <head>
                                    <meta http-equiv='refresh' content='0;{redirectUri}'>
                                </head>
                                <body></body>
                            </html>", OwinContext.Request.CallCancelled).ConfigureAwait(false));
                    }
                }
                catch
                {
                    model.Custom = new { };
                }
            }

            string json = JsonConvert.SerializeObject(new
            {
                model.AdditionalLinks,
                model.AllowRememberMe,
                model.AntiForgery,
                model.ClientLogoUrl,
                model.ClientName,
                model.ClientUrl,
                model.CurrentUser,
                model.Custom,
                model.ErrorMessage,
                model.ExternalProviders,
                model.LoginUrl,
                model.LogoutUrl,
                model.RememberMe,
                model.RequestId,
                model.SiteName,
                model.SiteUrl,
                model.Username,
                ReturnUrl = message.ReturnUrl == null ? "" : new Uri(message.ReturnUrl).ParseQueryString()["redirect_uri"]
            }, Formatting.None, jsonSerSettings);

            string loginPageHtmlInitialHtml = File.ReadAllText(PathProvider.MapStaticFilePath(AppEnvironment.GetConfig("LoginPagePath", "loginPage.html")));

            string loginPageHtmlFinalHtml = (await HtmlPageProvider.GetHtmlPageAsync(loginPageHtmlInitialHtml, OwinContext.Request.CallCancelled).ConfigureAwait(false))
                                            .Replace("{{model.LoginModel.toJson()}}", Microsoft.Security.Application.Encoder.HtmlEncode(json), StringComparison.InvariantCultureIgnoreCase);

            return(await ReturnHtmlAsync(model, loginPageHtmlFinalHtml, OwinContext.Request.CallCancelled).ConfigureAwait(false));
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            owinApp.Map("/core", coreApp =>
            {
                LogProvider.SetCurrentLogProvider(DependencyManager.Resolve <ILogProvider>());

                IdentityServerServiceFactory factory = new IdentityServerServiceFactory()
                                                       .UseInMemoryClients(DependencyManager.Resolve <IOAuthClientsProvider>().GetClients().ToArray())
                                                       .UseInMemoryScopes(ScopesProvider.GetScopes());

                IUserService ResolveUserService(IdentityServer3.Core.Services.IDependencyResolver resolver)
                {
                    OwinEnvironmentService owinEnv = resolver.Resolve <OwinEnvironmentService>();
                    IOwinContext owinContext       = new OwinContext(owinEnv.Environment);
                    IUserService userService       = owinContext.GetDependencyResolver().Resolve <IUserService>();

                    if (userService is UserService bitUserService)
                    {
                        bitUserService.CurrentCancellationToken = owinContext.Request.CallCancelled;
                    }

                    return(userService);
                }

                factory.UserService = new Registration <IUserService>(ResolveUserService);

                factory.EventService = new Registration <IEventService>(EventService);

                IViewService ResolveViewService(IdentityServer3.Core.Services.IDependencyResolver resolver)
                {
                    OwinEnvironmentService owinEnv = resolver.Resolve <OwinEnvironmentService>();
                    IOwinContext owinContext       = new OwinContext(owinEnv.Environment);
                    return(owinContext.GetDependencyResolver().Resolve <IViewService>());
                }

                factory.ViewService = new Registration <IViewService>(ResolveViewService);

                factory.RedirectUriValidator = new Registration <IRedirectUriValidator>(RedirectUriValidator);

                bool requireSslConfigValue = AppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false);

                string identityServerSiteName = AppEnvironment.GetConfig("IdentityServerSiteName", $"{AppEnvironment.AppInfo.Name} Identity Server");

                IdentityServerOptions identityServerOptions = new IdentityServerOptions
                {
                    SiteName           = identityServerSiteName,
                    SigningCertificate = AppCertificatesProvider.GetSingleSignOnCertificate(),
                    Factory            = factory,
                    RequireSsl         = requireSslConfigValue,
                    EnableWelcomePage  = AppEnvironment.DebugMode == true,
                    IssuerUri          = AppEnvironment.GetSsoIssuerName(),
                    CspOptions         = new CspOptions
                    {
                        // Content security policy
                        Enabled = false
                    },
                    Endpoints = new EndpointOptions
                    {
                        EnableAccessTokenValidationEndpoint   = true,
                        EnableAuthorizeEndpoint               = true,
                        EnableCheckSessionEndpoint            = true,
                        EnableClientPermissionsEndpoint       = true,
                        EnableCspReportEndpoint               = true,
                        EnableDiscoveryEndpoint               = true,
                        EnableEndSessionEndpoint              = true,
                        EnableIdentityTokenValidationEndpoint = true,
                        EnableIntrospectionEndpoint           = true,
                        EnableTokenEndpoint           = true,
                        EnableTokenRevocationEndpoint = true,
                        EnableUserInfoEndpoint        = true
                    },
                    EventsOptions = new EventsOptions
                    {
                        RaiseErrorEvents   = true,
                        RaiseFailureEvents = true
                    },
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        IdentityProviders = ConfigureIdentityProviders
                    }
                };

                foreach (IIdentityServerOptionsCustomizer customizer in Customizers)
                {
                    customizer.Customize(identityServerOptions);
                }

                coreApp.UseIdentityServer(identityServerOptions);
            });
        }
Exemplo n.º 29
0
 public MyAppDbContext(AppEnvironment appEnvironment, IDbConnectionProvider dbConnectionProvider)
     : base(appEnvironment.GetConfig <string>("AppConnectionString"), dbConnectionProvider)
 {
 }
Exemplo n.º 30
0
 public TestDbContext(AppEnvironment appEnvironment, IDbContextObjectsProvider dbContextCreationOptionsProvider)
     : base(appEnvironment.GetConfig <string>("TestDbConnectionString"), dbContextCreationOptionsProvider)
 {
 }