public LoginController(ILogger <LoginController> logger, LoginService loginService, IOptions <SecurityConfig> config, IClock systemClock) { this.logger = logger; this.loginService = loginService; this.systemClock = systemClock; this.config = config.Value; }
private void LoadSystemOptions( ) { this.originalConfig = Program.Config.Application.Security; var tmpLockSettings = this.originalConfig.LockWorkspace; var tmpLockAfterTime = tmpLockSettings.LockAfterTime; var tmpLockWorkspace = tmpLockAfterTime > 0; this.numericLockAfterTime.Value = (tmpLockWorkspace ? tmpLockAfterTime : 100); this.checkLockAfterTime.Checked = tmpLockWorkspace; this.numericLockAfterTime.Enabled = (this.checkLockAfterTime.Checked && this.checkLockAfterTime.Enabled); var tmpLockAfterGlobal = tmpLockSettings.LockGlobalTime; var tmpLockWorkStation = tmpLockAfterGlobal > 0; this.numericLockGlobalTime.Value = (tmpLockWorkStation ? tmpLockAfterGlobal : 200); this.checkLockGlobalTime.Checked = tmpLockWorkStation; this.numericLockGlobalTime.Enabled = (this.checkLockGlobalTime.Checked && this.checkLockGlobalTime.Enabled); this.colorComboRank0.Color = this.originalConfig.SecretRank.Rank0BackColor; this.colorComboRank1.Color = this.originalConfig.SecretRank.Rank1BackColor; this.colorComboRank2.Color = this.originalConfig.SecretRank.Rank2BackColor; this.colorComboRank3.Color = this.originalConfig.SecretRank.Rank3BackColor; this.textWorkDirectory.Text = Program.Config.WorkingDirectory; this.checkAutoRun.Checked = NativeShellHelper.GetStartWithWindows(ApplicationDefines.AutoRunName); }
public virtual EnterpriseAuthAndUserManager NewAuthManager(Config config, LogProvider logProvider, SecurityLog securityLog, FileSystemAbstraction fileSystem, JobScheduler jobScheduler, AccessCapability accessCapability) { SecurityConfig = GetValidatedSecurityConfig(config); IList <Realm> realms = new List <Realm>(SecurityConfig.authProviders.Count + 1); SecureHasher secureHasher = new SecureHasher(); EnterpriseUserManager internalRealm = CreateInternalRealm(config, logProvider, fileSystem, jobScheduler, securityLog, accessCapability); if (internalRealm != null) { realms.Add(( Realm )internalRealm); } if (SecurityConfig.hasLdapProvider) { realms.Add(new LdapRealm(config, securityLog, secureHasher)); } if (SecurityConfig.pluginAuthProviders.Count > 0) { ((IList <Realm>)realms).AddRange(CreatePluginRealms(config, securityLog, secureHasher, SecurityConfig)); } // Select the active realms in the order they are configured IList <Realm> orderedActiveRealms = SelectOrderedActiveRealms(SecurityConfig.authProviders, realms); if (orderedActiveRealms.Count == 0) { throw IllegalConfiguration("No valid auth provider is active."); } return(new MultiRealmAuthManager(internalRealm, orderedActiveRealms, CreateCacheManager(config), securityLog, config.Get(SecuritySettings.security_log_successful_authentication), SecurityConfig.propertyAuthorization, SecurityConfig.propertyBlacklist)); }
protected internal virtual SecurityConfig GetValidatedSecurityConfig(Config config) { SecurityConfig securityConfig = new SecurityConfig(config); securityConfig.Validate(); return(securityConfig); }
public static string CheckAccessByCookie() { var current = AuthCookie.GetCurrent(); var settings = SecurityConfig.GetCurrent(); var cookieNotFound = (current == null || current.SessionUid == null); AuthenticationDataDto dto = null; if (cookieNotFound || (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate())) { return(null); } else if (!settings.Cookie.CookieOnlyCheck) { dto = Access.Renew(current.SessionUid); if (dto == null) { return(null); } else { return(string.Format("{0}||{1}", dto.Username.Trim(), dto.Roles.Trim())); } } else if (settings.Cookie.CookieOnlyCheck) { return(string.Format("{0}||{1}", current.Username.Trim(), current.UserRoles.Trim())); } return(null); }
internal static bool IsSessionActive(string sessionId) { if (string.IsNullOrEmpty(sessionId)) { return(false); } var settings = SecurityConfig.GetCurrent(); var current = AuthCookie.GetCurrent(); ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>(); var userObject = authenticationService.GetUserBySessionId(sessionId); bool isActive = false; if (userObject != null) { if ((!userObject.CurrentSessionId.HasValue || sessionId != userObject.CurrentSessionId.ToString()) || (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate()) || ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)) { if (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate()) { isActive = true; } } } return(isActive); }
public void AddUser(User userToAdd, ref ValidationStateDictionary states) { var v = new UserValidator().Validate(userToAdd, validationRepositoryInstance); if (v.Errors.Count > 0) { states.Add(typeof(User), v); return; } var settings = SecurityConfig.GetCurrent(); if (settings.Cookie.PasswordHashed && !string.IsNullOrEmpty(userToAdd.Password)) { userToAdd.Password = PasswordHash.Hash(userToAdd.Username.ToLower(), userToAdd.Password); } else if (userToAdd.AccountType == Constants.AccountType.ADLocal) { userToAdd.Password = "******"; } userToAdd.ApprovalStatus = Constants.ApprovalStatus.Pending; userToAdd.IsFirstLogIn = true; userToAdd.RoleId = userToAdd.UserRole.RoleId; //check if the AccountExpires and set the number of days for Accountexpiry updateUserAccountExpiry(userToAdd); repositoryInstance.AddUser(userToAdd); RegistrationNotification(userToAdd, true); }
public static void Load() { if (!System.IO.File.Exists(Files.ConfigurationPath)) { Logger.Write("Configuration does not exist. Loading defaults.", LogType.System); LoadDefaults(); return; } string json = System.IO.File.ReadAllText(Files.ConfigurationPath); ConfigFile file = JsonConvert.DeserializeObject <ConfigFile>(json); if (file == null) { Logger.Write("Unable to load Config. Loading defaults.", LogType.Warning); LoadDefaults(); } else { Basic = file.Basic; Chat = file.Chat; Worlds = file.Worlds; Security = file.Security; Logging = file.Logging; Advanced = file.Advanced; IRC = file.IRC; Misc = file.Misc; } }
public RequiredScopesMiddleware(RequestDelegate next, SecurityConfig config) { _next = next; _authType = config.AuthenticationType; _requiredScopes = config.RequiredScopes; _trustedClients = config.TrustedClients; }
public DnsUpdater(IOptions <SecurityConfig> securityConfig, IOptions <DnsConfig> dnsConfig, IGetCurrentIpAddress ipAddressLookup, ILogger <DnsUpdater> logger) { _securityConfig = securityConfig.Value; _dnsConfig = dnsConfig.Value; _ipAddressLookup = ipAddressLookup; _logger = logger; }
public UserRepository(IOptions <SecurityConfig> config, IImageWriter imageWriter, PolloPolloContext context) { _config = config.Value; _imageWriter = imageWriter; _context = context; _deviceAddress = "AymLnfCdnKSzNHwMFdGnTmGllPdv6Qxgz1fHfbkEcDKo"; _obyteHub = "obyte.org/bb"; }
private static SecurityConfig ReadSecurityConfig(XmlReader reader) { var tmpSecurityConfig = new SecurityConfig(); if (SkipEmptyElement(reader)) { return(tmpSecurityConfig); } Debug.Assert(reader.NodeType == XmlNodeType.Element); reader.ReadStartElement(); reader.MoveToContent(); while (true) { var tmpNodeType = reader.NodeType; if (tmpNodeType == XmlNodeType.None || tmpNodeType == XmlNodeType.EndElement) { break; } if (tmpNodeType == XmlNodeType.Element) { switch (reader.LocalName) { default: reader.Skip(); break; case "Account": ReadAccountConfig(tmpSecurityConfig.CurrentAccount, reader); break; case "LockWorkspace": tmpSecurityConfig.LockWorkspace = ReadLockWorkspaceConfig(reader); break; case "MasterPassword": tmpSecurityConfig.MasterPassword = ReadMasterPasswordConfig(reader); break; case "Clipboard": tmpSecurityConfig.Clipboard = ReadClipboardSettings(reader); break; case "SecretRank": tmpSecurityConfig.SecretRank = ReadSecretRankSettings(reader); break; } reader.MoveToContent(); } } reader.ReadEndElement(); return(tmpSecurityConfig); }
public SignatureKeyGenerationWorker(ILogger <SignatureKeyGenerationWorker> logger, IOptions <SecurityConfig> options, ISignatureKeyContainer signatureKeyContainer, IKeyStoreClient keyStoreClient, IMetrics metrics) { _logger = logger; _signatureKeyContainer = signatureKeyContainer; _keyStoreClient = keyStoreClient; _metrics = metrics; _config = options.Value; }
private DbConnection OpenConnection() { this.currentFactory = DbProviderFactories.GetFactory(SecurityConfig.GetInstance().SqlProvider); DbConnection connection = this.currentFactory.CreateConnection(); connection.ConnectionString = this.MountConnection(); connection.Open(); return(connection); }
protected void Application_Start() { SecurityConfig.ConfigureSecurity(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); SecurityConfig.InitializeComponents(); Bootstrapper.Initialise(); ModelBinders.Binders.Add(typeof(CaptchaViewModel), new CaptchaModelBinder()); }
public ActionResult LogOut() { Access.SignOut(_securityService); if (!string.IsNullOrEmpty((Request.QueryString["xxkeyxx"] as string))) { Danger(string.Format("You have been logged out due to inactivity for {0} minutes. Please log in again.", SecurityConfig.GetCurrent().Cookie.Timeout), true); } //var url = string.Format("{0}/{1}", Helper.GetRootURL(), SecurityConfig.GetCurrent().Login.Page); return(RedirectToAction(SecurityConfig.GetCurrent().Login.Page)); }
public static void AddCustomCors(this IServiceCollection services, EnumCors enumCors = EnumCors.AllowSpecificOrigin) { string corsName = enumCors.ToString(); services.AddCors(o => { { o.AddPolicy(corsName, SecurityConfig.GetCORSPolicy()); } }); }
/// <summary> /// Loads the default configs /// </summary> public static void LoadDefaults() { Basic = new BasicConfig(); Chat = new ChatConfig(); Worlds = new WorldConfig(); Security = new SecurityConfig(); Logging = new LoggingConfig(); Advanced = new AdvancedConfig(); IRC = new IRCConfig(); Misc = new MiscConfig(); }
public FirewallRulesUpdater( IOptions <SecurityConfig> securityConfig, IOptions <FirewallConfig> firewallConfig, IGetCurrentIpAddress ipAddressLookup, ILogger <FirewallRulesUpdater> logger) { _securityConfig = securityConfig.Value; _firewallConfig = firewallConfig.Value; _ipAddressLookup = ipAddressLookup; _logger = logger; }
public IDBConnection AddClaimsDefaults(ClaimsPrincipal claimsPrincipal) { var defaults = SecurityConfig.GetClaimsDefaultForDataConfig(); foreach (var claim in defaults) { AddDefaultParameter(CreateParameter(claim.Key, IdentityManager.GetClaimValue(claimsPrincipal, claim.Value)), false); } return(this); }
public static void ConfigureInternalSecrets(this IApplicationBuilder app, IConfiguration config) { DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance); SecurityConfig.GetInstance() .AddSqlServer(config["SqlConnection:Server"]) .AddSqlUID(config["SqlConnection:uid"]) .AddSqlPWD(config["SqlConnection:pwd"]) .AddSqlDatabase(config["SqlConnection:database"]) .AddSqlTimeout(config["SqlConnection:timeout"]) .AddSqlProvider(config["SqlConnection:provider"]); }
private string MountConnection() { StringBuilder b = new StringBuilder(); b.Append($@"Data Source={SecurityConfig.GetInstance().SqlServer};"); b.Append($@"Initial Catalog={SecurityConfig.GetInstance().SqlDatabase};"); b.Append($@"User ID={SecurityConfig.GetInstance().SqlUID};"); b.Append($@"Password={SecurityConfig.GetInstance().SqlPWD};"); b.Append($@"Persist Security Info={true};"); b.Append($@"Connect Timeout={SecurityConfig.GetInstance().SqlTimeout};"); return(b.ToString()); }
private static void SetUpCookieAuth(IServiceCollection services, IConfiguration configuration) { //services.Configure<SecurityConfig>(Configuration.GetSection("Security")); //services.Configure<JsonWebTokenConfig>(Configuration.GetSection("JsonWebToken")); SecurityConfig security = new SecurityConfig(); JsonWebTokenConfig jsonWebTokenConfig = new JsonWebTokenConfig(); configuration.GetSection("SecurityConfig").Bind(security); configuration.GetSection("JsonWebTokenConfig").Bind(jsonWebTokenConfig); CookieBuilder cookie = new CookieBuilder(); cookie.Domain = security.AppDomain; cookie.Name = security.CookieName; cookie.HttpOnly = true; cookie.Path = "/"; cookie.SameSite = SameSiteMode.None; cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; cookie.MaxAge = TimeSpan.FromMinutes(60 * 24 * 90); // If you don't want the cookie to be automatically authenticated and assigned to // HttpContext.User, remove the CookieAuthenticationDefaults.AuthenticationScheme // parameter passed to AddAuthentication. services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.Cookie = cookie; options.SlidingExpiration = true; options.TicketDataFormat = new Sabio.Web.Core.Services.TokenSecureDataFormat(jsonWebTokenConfig); options.AccessDeniedPath = "/unauthorized"; options.LoginPath = "/login"; options.LogoutPath = "/logout"; options.Events = new CookieAuthenticationEvents(); options.Events.OnRedirectToAccessDenied = RedirectContext; options.Events.OnRedirectToLogin = RedirectContext; }); services.AddAuthorization(authorizeOptions => { authorizeOptions.AddPolicy("defaultpolicy", b => { b.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme); b.RequireAuthenticatedUser(); }); }); }
/// <summary> /// Initialize the securityMechContext based on the security package type /// </summary> /// <param name="mechType">security mechanism type</param> /// <param name="inToken">the input security token</param> /// <exception cref="InvalidOperationException">Thrown if could not find the configuration.</exception> /// <exception cref="InvalidOperationException">Thrown when security configuration is unknown</exception> private void InitializeSecurityContext(MechType mechType, byte[] inToken) { SpngClientContext clientContext = this.client.Context as SpngClientContext; SecurityPackageType authType = SpngUtility.ConvertMechType(mechType); CurrentSecurityConfig = SpngUtility.GetSecurityConfig(this.securityConfigList, authType); if (CurrentSecurityConfig == null) { throw new InvalidOperationException("Missing configuration for " + authType.ToString()); } if (securityMechContext != null) { // re-enter. Nothing need to do return; } if (CurrentSecurityConfig.GetType() == typeof(KerberosClientSecurityConfig)) { KerberosClientSecurityConfig kileConfig = CurrentSecurityConfig as KerberosClientSecurityConfig; securityMechContext = new KerberosClientSecurityContext( kileConfig.ServiceName, kileConfig.ClientCredential, KerberosAccountType.User, kileConfig.KdcIpAddress, kileConfig.KdcPort, kileConfig.TransportType, kileConfig.SecurityAttributes); } else if (CurrentSecurityConfig.GetType() == typeof(NlmpClientSecurityConfig)) { NlmpClientSecurityConfig nlmpConfig = CurrentSecurityConfig as NlmpClientSecurityConfig; NlmpClientCredential cred = new NlmpClientCredential( nlmpConfig.TargetName, nlmpConfig.DomainName, nlmpConfig.AccountName, nlmpConfig.Password); securityMechContext = new NlmpClientSecurityContext(cred, nlmpConfig.SecurityAttributes); } else if (CurrentSecurityConfig.GetType() == typeof(SspiClientSecurityConfig)) { throw new InvalidOperationException("Only support Kerberos security config and NTLM security config"); } else { throw new InvalidOperationException("unknown security config"); } }
public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (!_authorizationStatus) { var settings = SecurityConfig.GetCurrent(); var current = AuthCookie.GetCurrent(); var sessionID = string.Empty; if (current != null) { sessionID = current.SessionUid; current.Delete(); } string loginUrl = (settings.Login.Url + settings.Login.Page).ToLower(); var rawUrl = filterContext.HttpContext.Request.RawUrl; var redirectUrl = string.Empty; if (!string.IsNullOrEmpty(rawUrl) && rawUrl != loginUrl) { if (!rawUrl.Contains("xxkeyxx")) //auto logout key { if (!Access.IsSessionActive(sessionID)) { redirectUrl = "?ReturnUrl=" + HttpUtility.UrlEncode(rawUrl, filterContext.HttpContext.Request.ContentEncoding); } else { redirectUrl = string.Empty; } AddAlert(AlertStyles.Danger, "Your session has expired or you do not have access to the page you are trying to access.", true); } else { AddAlert(AlertStyles.Danger, string.Format("You have been logged out due to inactivity for {0} minutes. Please log in again.", SecurityConfig.GetCurrent().Cookie.Timeout), true); } } if (!string.IsNullOrEmpty(sessionID)) { var context = HttpContext.Current; var securityService = ((IContainer)context.Application["container"]).Resolve <ISecurityService>(); securityService.SignOut(sessionID); } filterContext.Result = new RedirectResult(loginUrl + redirectUrl); return; } }
public ActionResult ConfigEdit(SecurityConfig model) { var config = dbContextService.Single <SecurityConfig>(model.Id); config.Name = model.Name; config.Type = model.Type; config.LatestVersion = model.LatestVersion; config.Rate = model.Rate; config.Status = model.Status; config.CreateDateTime = DateTime.Now; dbContextService.Update <SecurityConfig>(config); return(RedirectToAction("ConfigList")); }
public ActionResult ConfigAdd(SecurityConfig model) { var exist = dbContextService.Exists <SecurityConfig>(x => x.Type == model.Type); if (exist) { TempData["errorMsg"] = "该配置已经存在!"; return(View()); } var ret = dbContextService.Add <SecurityConfig>(model); return(RedirectToAction("ConfigList")); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); BundleConfig.RegisterBundles(BundleTable.Bundles); WebApiConfig.Register(GlobalConfiguration.Configuration); SecurityConfig.Register(GlobalConfiguration.Configuration); HubConfig.Register(RouteTable.Routes); //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize(); Database.SetInitializer(new DropCreateDatabaseIfModelChanges <TodoContext>()); EFWarmup.Run(); }
public AuthenticationDataDto Renew(string sessionId) { var userObject = repositoryInstance.GetUserBySessionId(sessionId); if (userObject == null) { return(null); } var settings = SecurityConfig.GetCurrent(); bool renewSucceed = true; if ((!userObject.CurrentSessionId.HasValue || sessionId != userObject.CurrentSessionId.ToString()) || (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) < Helper.GetLocalDate()) || ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)) { if (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) < Helper.GetLocalDate()) { userObject.IsOnline = false; userObject.CurrentSessionId = null; } renewSucceed = false; } else { if (settings.Cookie.SlidingExpiration) { userObject.LastActivityDate = Helper.GetLocalDate(); } } UpdateRenewSucceed(userObject); AuthenticationDataDto auth = null; if (renewSucceed) { auth = new AuthenticationDataDto(); { auth.SessionId = userObject.CurrentSessionId.Value.ToString(); auth.Username = userObject.Username; auth.BranchCode = userObject.BranchID; auth.Roles = userObject.UserRole == null ? null : userObject.UserRole.RoleName; auth.FullName = string.Format("{0} {1}", userObject.FirstName, userObject.LastName); auth.IsRoleSet = !(userObject.AccountType == Constants.AccountType.ADFinacle || userObject.AccountType == Constants.AccountType.LocalFinacle); } } return(auth); }