コード例 #1
0
        private static void CreateThreadPrincipalAndAuthCookie(AuthenticationDataDto currentUser, SecurityConfig settings)
        {
            //create the cookie
            Identity  identity  = new Identity(new Guid(currentUser.SessionId), currentUser.Username, currentUser.Roles, currentUser.FullName, currentUser.BranchCode, currentUser.AccountType);
            Principal principal = new Principal(identity, identity.Roles, identity.AccountType);

            System.Web.HttpContext.Current.User      = principal;
            System.Threading.Thread.CurrentPrincipal = principal;

            var cookie = new AuthCookie();

            {
                cookie.SessionUid = currentUser.SessionId;
                if (settings.Cookie.CookieOnlyCheck)
                {
                    cookie.Username    = currentUser.Username;
                    cookie.UserRoles   = currentUser.Roles;
                    cookie.BranchCode  = currentUser.BranchCode;
                    cookie.AccountType = currentUser.AccountType;
                    cookie.AuthExpiry  = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout);
                }
                cookie.Save();
            }

            if (!settings.Cookie.CookieOnlyCheck)
            {
                HttpContext.Current.Cache.Insert(currentUser.SessionId, currentUser, null, DateTime.UtcNow.AddSeconds(30), System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }
コード例 #2
0
        private static void SetAuthMode(AuthenticationDataDto currentUser, ref bool validateWithAD, ref bool useFinacleRole)
        {
            if (currentUser == null)
            {
                validateWithAD = true;
                useFinacleRole = true;
            }

            if (currentUser != null && !currentUser.IsPasswordSet && !currentUser.IsRoleSet)
            {
                validateWithAD = true;
                useFinacleRole = true;
            }
            if (currentUser != null && !currentUser.IsPasswordSet && currentUser.IsRoleSet)
            {
                validateWithAD = true;
                useFinacleRole = false;
            }
            if (currentUser != null && currentUser.IsPasswordSet && !currentUser.IsRoleSet)
            {
                validateWithAD = false;
                useFinacleRole = true;
            }
            if (currentUser != null && currentUser.IsPasswordSet && currentUser.IsRoleSet)
            {
                validateWithAD = false;
                useFinacleRole = false;
            }
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        private static bool ValidateLocalUserRole(ValidationStateDictionary states, AuthenticationDataDto currentUser)
        {
            bool finalStatus = true;

            if (currentUser != null)
            {
                if (string.IsNullOrEmpty(currentUser.Roles))
                {
                    ValidationState v = new ValidationState();
                    v.Errors.Add(new ValidationError("General.InvalidRole", currentUser.Roles, string.Format("User role {0} does not exist on this application, contact the administrator", currentUser.Roles)));
                    states.Add(typeof(LogInDto), v);
                    return(finalStatus);
                }
            }
            else
            {
                ValidationState v = new ValidationState();
                v.Errors.Add(new ValidationError("General.InvalidRole", currentUser.Roles, string.Format("User role {0} does not exist on this application, contact the administrator", currentUser.Roles)));
                states.Add(typeof(LogInDto), v);
                return(finalStatus);
            }
            return(finalStatus);
        }
コード例 #6
0
        public AuthenticationDataDto SignIn(string username, string password, bool sessionBased, ref ValidationStateDictionary states)
        {
            ValidationState v = new ValidationState();

            if (string.IsNullOrEmpty(username))
            {
                v.Errors.Add(new ValidationError("Username.UsernameRequiredError", username, "Username is not set."));
            }
            if (string.IsNullOrEmpty(password))
            {
                v.Errors.Add(new ValidationError("Password.PasswordRequiredError", password, "Password is not set"));
            }

            if (v.Errors.Count > 0)
            {
                states.Add(typeof(LogInDto), v);
                return(new AuthenticationDataDto()
                {
                    AppAuthenticationFailed = true
                });
            }

            var userObject = repositoryInstance.GetUser(username);

            if (userObject == null)
            {
                v.Errors.Add(new ValidationError("Password.InvalidUsername", username, "Invalid Username or Password"));
                states.Add(typeof(LogInDto), v);
                return(null);
            }

            string lastLogin = userObject.LastLogInDate.HasValue ?
                               userObject.LastLogInDate.Value.ToString("dd-MM-yyyy HH:mm:ss")
                : Helper.GetLocalDate().ToString("dd-MM-yyyy HH:mm:ss");

            cacheService.AddAndTieToSession(string.Format("UserLastLogIn-{0}", userObject.Username), lastLogin);

            var roleID = GetRoleList().Where(f => f.RoleName == Constants.General.AdministratorRoleName).Select(r => r.RoleId).FirstOrDefault();

            if (!IsBusinessHour())
            {
                //allow administrator log in outside business hours.
                if (roleID != userObject.RoleId)
                {
                    v.Errors.Add(new ValidationError("User.NonBusinessHoursLoginError", username, "Login outside business hours is not allowed, Please try logging in during business hours."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //Check if account is not locked,is approved and not deleted.
            if ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)
            {
                v.Errors.Add(new ValidationError("Username.AccountLocked", username, "This account is inactive, has been locked or has been Deleted."));
                states.Add(typeof(LogInDto), v);

                return(new AuthenticationDataDto()
                {
                    AppAuthenticationFailed = true
                });
            }

            //check if user is Dormented.
            if (userObject.LastLogInDate == null)
            {
                //exclude administrator account from being dormant
                if (roleID != userObject.RoleId)
                {
                    int dormentNumberOfDays = NewUserIDDormentNumberDays();
                    if ((Helper.GetLocalDate() - (DateTime)userObject.CreationDate).Days >= dormentNumberOfDays)
                    {
                        UpdateUserDetails(userObject, isDorment: true);
                        v.Errors.Add(new ValidationError("Username.AccountDormented", username, "This account is Dormant as user has not logged for " + dormentNumberOfDays + " days from the day of account creation. Please contact the administrator."));
                        states.Add(typeof(LogInDto), v);
                        return(new AuthenticationDataDto()
                        {
                            AppAuthenticationFailed = true
                        });
                    }
                }
            }

            //prevent multi terminal login
            if (userObject.IsOnline)
            {
                var settings    = SecurityConfig.GetCurrent();
                var timeOutDate = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout * -1);
                if (userObject.LastActivityDate.HasValue && userObject.LastActivityDate.Value >= timeOutDate)
                {
                    v.Errors.Add(new ValidationError("Username.MultiTeminalLogin", username, "You are currently logged in on another terminal. Kindly log out there and retry."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //if last log in date/last activity date more than 90 days ago, refuse log in and lock the account
            if (userObject.LastLogInDate.HasValue && userObject.LastLogInDate.Value.Date < Helper.GetLocalDate().AddDays(ActiveUserIDDormentNumberDays()))
            {
                //exclude administrator account from being dormant
                if (roleID != userObject.RoleId)
                {
                    repositoryInstance.UpdateBadPasswordCount(username, true);
                    UpdateUserDetails(userObject, isDorment: true);
                    v.Errors.Add(new ValidationError("Username.AccountDormented", username, "This account is Dormant. Please contact the administrator."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //Check if the Account is Expired
            if (userObject.AccountExpiryDate != null)
            {
                if (userObject.AccountExpiryDate < DateTime.Now)
                {
                    //exclude administrator account from expiring
                    if (roleID != userObject.RoleId)
                    {
                        UpdateUserDetails(userObject, isAccountExpired: true);
                        v.Errors.Add(new ValidationError("Username.AccountExpired", username, "This account is Expired. Please contact the administrator."));
                        states.Add(typeof(LogInDto), v);
                        return(new AuthenticationDataDto()
                        {
                            AppAuthenticationFailed = true
                        });
                    }
                }
            }

            if (userObject.Password != "Dummy" && (userObject.AccountType == Constants.AccountType.LocalLocal || userObject.AccountType == Constants.AccountType.LocalFinacle))
            {
                //check the password match
                if (userObject.Password != password)
                {
                    //v.Errors.Add(new ValidationError("Username.InvalidUsername", username, "Invalid Username or Password"));
                    v.Errors.Add(new ValidationError("Password.InvalidPassword", password, "Invalid Username or Password"));
                    var settings    = SecurityConfig.GetCurrent();
                    var lockAccount = userObject.BadPasswordCount + 1 >= settings.Cookie.MaximumPasswordRetries;
                    repositoryInstance.UpdateBadPasswordCount(username, lockAccount);
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            AuthenticationDataDto auth = new AuthenticationDataDto();

            {
                auth.SessionId     = Helper.GetNextGuid().ToString();
                auth.Username      = username;
                auth.Roles         = userObject.UserRole != null ? userObject.UserRole.RoleName : null;
                auth.BranchCode    = userObject.BranchID;
                auth.IsFirstLogIn  = userObject.IsFirstLogIn;
                auth.FullName      = string.Format("{0} {1}", userObject.FirstName, userObject.LastName);
                auth.IsPasswordSet = userObject.Password != "Dummy" && (userObject.AccountType == Constants.AccountType.LocalLocal || userObject.AccountType == Constants.AccountType.LocalFinacle);
                auth.IsRoleSet     = userObject.AccountType == Constants.AccountType.ADLocal || userObject.AccountType == Constants.AccountType.LocalLocal; // userObject.UserRole != null && !string.IsNullOrEmpty(userObject.UserRole.RoleName);
                auth.AccountType   = userObject.AccountType;
            }

            if (sessionBased)
            {
                UpdateLogInSucceed(username, auth.SessionId);
            }

            return(auth);
        }
コード例 #7
0
        private static ISecurityService PerfomAccessCheck(HttpContextBase context)
        {
            var settings = SecurityConfig.GetCurrent();
            var current  = AuthCookie.GetCurrent();
            ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>();

            var cookieNotFound = (current == null || current.SessionUid == null);
            var cookiedDeleted = false;

            AuthenticationDataDto dto = null;

            if (cookieNotFound)
            {
                if (current != null)
                {
                    current.Delete();
                    cookiedDeleted = true;
                }
            }
            else if (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate())
            {
                current.Delete();
                cookiedDeleted = true;
            }
            else if (!settings.Cookie.CookieOnlyCheck)
            {
                dto = Access.Renew(current.SessionUid, authenticationService);
                if (dto == null)
                {
                    current.Delete();
                    cookiedDeleted = true;
                }
            }

            if (!cookiedDeleted)
            {
                if (dto == null)
                {
                    dto = new AuthenticationDataDto();
                }

                Identity identity = new Identity(new Guid(current.SessionUid),
                                                 settings.Cookie.CookieOnlyCheck ? current.Username : dto.Username,
                                                 settings.Cookie.CookieOnlyCheck ? current.UserRoles : dto.Roles, dto.FullName,
                                                 settings.Cookie.CookieOnlyCheck ? current.BranchCode : dto.BranchCode,
                                                 settings.Cookie.CookieOnlyCheck ? current.AccountType : dto.AccountType);
                var principal = new Principal(identity, identity.Roles, identity.AccountType);
                context.User            = principal;
                Thread.CurrentPrincipal = principal;

                if (settings.Cookie.SlidingExpiration && settings.Cookie.CookieOnlyCheck)
                {
                    current.AuthExpiry = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout);
                    current.Save();
                }
            }

            var ip = context.Request.UserHostAddress;

            return(authenticationService);
        }
コード例 #8
0
        private static AuthenticationDataDto FinacleAuthorization(string username, ISecurityService authenticationService, IFinacleRepository finacleRepository, AuthenticationDataDto currentUser, AuthenticationResponse result)
        {
            //get finacle role
            FinacleRole finacleRole = finacleRepository.GetUserRoleFromFlexcube(username);

            if (finacleRole == null)
            {
                finacleRole = new FinacleRole()
                {
                    UserID = username, BranchCode = null, ApplicationName = string.Empty
                }
            }
            ;

            var roleId = authenticationService.GetRoleList().Where(r => r.RoleName.ToLower() == finacleRole.ApplicationName.ToLower()).Select(k => k.RoleId).FirstOrDefault();

            if (currentUser == null)
            {
                //create the user record for session  management purpose, only for AD/Finacle users logging in for the first time,
                //if role is recognised in this application
                var userObject = new User()
                {
                    BadPasswordCount = 0,
                    CreationDate     = Helper.GetLocalDate(),
                    CurrentSessionId = Helper.GetNextGuid(),
                    Email            = result.Email,
                    FirstName        = result.FirstName,
                    //ApprovalStatus = true,
                    IsFirstLogIn     = false,
                    Initial          = string.Empty,
                    LastLogInDate    = Helper.GetLocalDate(),
                    IsLockedOut      = false,
                    IsOnline         = true,
                    LastActivityDate = Helper.GetLocalDate(),
                    LastName         = result.LastName,
                    InitiatedBy      = username,
                    //ApprovedBy = "NULL",
                    Username       = username,
                    Telephone      = "N/A",
                    Password       = "******",
                    AccountType    = Constants.AccountType.ADFinacle,
                    ApprovalStatus = Constants.ApprovalStatus.Approved,
                    BranchID       = finacleRole.BranchCode,
                    IsDeleted      = false,
                    UserRole       = new Role()
                    {
                        RoleId = roleId
                    }
                };

                if (roleId != Guid.Empty)
                {
                    authenticationService.AddUserForSessionMgmt(userObject);
                }

                currentUser = new AuthenticationDataDto();
                {
                    currentUser.SessionId     = userObject.CurrentSessionId.ToString();
                    currentUser.Username      = username;
                    currentUser.Roles         = finacleRole.ApplicationName;
                    currentUser.IsFirstLogIn  = false;
                    currentUser.FullName      = string.Format("{0} {1}", userObject.FirstName, userObject.LastName);
                    currentUser.IsPasswordSet = false;
                    currentUser.BranchCode    = finacleRole.BranchCode;
                }
            }

            //with finacle authorization, we check whether the locally saved role
            //is the same as we got from Finacle, if not we update the local db.
            //and we always override local role even if available
            //this ensure if the role changed in Finacle it is inherited in the application.
            //we also ensure if user branch in finacle has changed, is changed here too
            if ((currentUser.Roles.ToLower() != finacleRole.ApplicationName.ToLower() && roleId != Guid.Empty) || (currentUser.BranchCode != finacleRole.BranchCode && !string.IsNullOrEmpty(finacleRole.BranchCode)))
            {
                authenticationService.UpdateUserRoleUserBranch(currentUser.Username, roleId, finacleRole.BranchCode);
                currentUser.Roles      = finacleRole.ApplicationName;
                currentUser.BranchCode = finacleRole.BranchCode;
            }


            return(currentUser);
        }
コード例 #9
0
        public static bool SignIn(string username, string password, string tokenCode, ISecurityService authenticationService, IFinacleRepository finacleRepository, out bool isFirstLogIn, ref ValidationStateDictionary states)
        {
            isFirstLogIn = false;
            AuthenticationDataDto currentUser = null;
            bool validateWithAD = false;
            bool useFinacleRole = false;
            var  hashedPassword = string.Empty;
            var  settings       = SecurityConfig.GetCurrent();

            if (settings.Cookie.PasswordHashed && !string.IsNullOrEmpty(password))
            {
                var lowerUsername = string.Empty;
                if (!string.IsNullOrEmpty(username))
                {
                    lowerUsername = username.ToLower();
                }
                hashedPassword = PasswordHash.Hash(lowerUsername, password);
            }
            currentUser = authenticationService.SignIn(username, hashedPassword, true, ref states);
            if (currentUser != null)
            {
                if (currentUser.AppAuthenticationFailed)
                {
                    return(false);
                }
            }
            states.Clear();

            SetAuthMode(currentUser, ref validateWithAD, ref useFinacleRole);

            AuthenticationResponse result = new AuthenticationResponse();

            if (validateWithAD)
            {
                var ADResult = ADAuthentication(username, password, tokenCode, authenticationService, finacleRepository, states, settings, ref result);
                if (!ADResult)
                {
                    if (currentUser != null)
                    {
                        authenticationService.SignOut(currentUser.SessionId);
                    }
                    return(false);
                }
            }

            if (useFinacleRole)
            {
                currentUser = FinacleAuthorization(username, authenticationService, finacleRepository, currentUser, result);
            }
            else
            {
                if (!ValidateLocalUserRole(states, currentUser))
                {
                    if (currentUser != null)
                    {
                        authenticationService.SignOut(currentUser.SessionId);
                    }
                    return(false);
                }
            }

            if (!ValidateRoleAndUser(username, authenticationService, states, currentUser))
            {
                if (currentUser != null)
                {
                    authenticationService.SignOut(currentUser.SessionId);
                }
                return(false);
            }

            if (!Check2FA(username, tokenCode, states, currentUser, settings))
            {
                if (currentUser != null)
                {
                    authenticationService.SignOut(currentUser.SessionId);
                }
                return(false);
            }

            CreateThreadPrincipalAndAuthCookie(currentUser, settings);

            isFirstLogIn = validateWithAD == true ? false : currentUser.IsFirstLogIn;

            //if (useFinacleRole) /no longer needed.
            //{
            //    //cache the role, so that we don't go back to finacle on every session renewal
            //    ICacheService cacheService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve<ICacheService>();
            //    CacheItemPolicy policy = new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, settings.Cookie.Timeout + 1, 0) };
            //    cacheService.Add(string.Format("UserSessionID:{0}", currentUser.SessionId), currentUser.Roles, policy);
            //}
            return(true);
        }
コード例 #10
0
        private static bool Check2FA(string username, string tokenCode, ValidationStateDictionary states, AuthenticationDataDto currentUser, SecurityConfig settings)
        {
            bool status2 = true;

            if (settings.Cookie.Enable2FA)
            {
                var status = (currentUser.IsPasswordSet) && settings.Cookie.ExemptLocalAccountFrom2FA;

                if (!status)
                {
                    var response = Auth2FAresponse(new Authentication2FARequest()
                    {
                        TokenCode = tokenCode, UserID = username
                    });
                    if (response.ResponseCode != "0")
                    {
                        ValidationState v = new ValidationState();
                        v.Errors.Add(new ValidationError("TokenCode.InvalidTokenCode", tokenCode, response.ResponseDescription)); //"Invalid token code"
                        states.Add(typeof(LogInDto), v);
                        status2 = false;
                    }
                }
            }
            return(status2);
        }
コード例 #11
0
        private static bool ValidateRoleAndUser(string username, ISecurityService authenticationService, ValidationStateDictionary states, AuthenticationDataDto currentUser)
        {
            if (currentUser == null)
            {
                ValidationState v = new ValidationState();
                v.Errors.Add(new ValidationError("Username.InvalidUsername", username, "Invalid Username or Password"));
                states.Add(typeof(LogInDto), v);
                return(false);
            }

            var localRole = authenticationService.GetRoleList().Where(f => f.RoleName.ToLower() == currentUser.Roles.ToLower()).Select(j => j.RoleName).FirstOrDefault();

            if (string.IsNullOrEmpty(localRole))
            {
                ValidationState v = new ValidationState();
                v.Errors.Add(new ValidationError("General.InvalidRole", currentUser.Roles, string.Format("User role {0} does not exist on this application, contact the administrator", currentUser.Roles)));
                states.Add(typeof(LogInDto), v);
                return(false);
            }
            return(true);
        }