Esempio n. 1
0
 /// <summary>
 /// Method to revoke/invalidate authentication token
 /// </summary>
 /// <param name="AuthToken"></param>
 /// <param name="UserType">type of user to be validated</param>
 /// <returns></returns>
 public bool revokeAuthToken(string AuthToken)
 {
     try
     {
         string AES_KEY      = CommonUtility.GetAppSettingKey(Constants.AuthToken.AES_KEY);
         string AES_SALT     = CommonUtility.GetAppSettingKey(Constants.AuthToken.AES_SALT);
         int    SaltLength   = Convert.ToInt32(CommonUtility.GetAppSettingKey(Constants.AuthToken.SaltLength));
         var    TokenBody    = CryptoUtility.Decrypt(AuthToken, AES_KEY, AES_SALT);
         var    LstTokenBody = JLT.Common.Utility.StringUtility.SplitString(TokenBody, "##");
         var    LstInnerMsg  = JLT.Common.Utility.StringUtility.SplitString(LstTokenBody[0], Constants.AuthToken.SeperatorString); //InnerMsg = UserID + Role + IPAddress + CryptoUtility.GenerateTimeStamp();
         var    TokenHash    = LstTokenBody[1];
         using (var objTokenDBService = new TokenDBService())
         {
             return(objTokenDBService.ChangeHashSalt(LstInnerMsg[0], CryptoUtility.GenerateSalt(SaltLength)));
         }
     }
     catch (MySqlException odbcEx)
     {
         throw odbcEx;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 2
0
        public DtoTokenResponse GetNewTokenFromRefreshToken(string tokenEncrypted)
        {
            var token = CryptoUtility.Decrypt(tokenEncrypted, _tokenProviderOptions.RefreshTokenSigningKey);

            var data   = Convert.FromBase64String(token);
            var obj    = ByteArrayToObject(data) as RefreshTokenPayloadModel;
            var claims = JsonConvert.DeserializeObject <IEnumerable <Claim> >(obj.Claims, new ClaimConverter());

            var when = DateTime.FromBinary(BitConverter.ToInt64(obj.TimeWithKey, 0));

            if (when < DateTime.UtcNow.AddHours(-4))
            {
                throw new LogicException(ExceptionMessage.ExpiredRefreshToken);
            }

            var userId = claims.First(x => x.Type == "sub")
                         .Value;

            var encodedJwt = GetJwt(claims, DateTime.UtcNow);

            if ((DateTime.UtcNow - when).Hours > 3)
            {
                tokenEncrypted = GetRefreshToken(claims, userId);
            }

            return(new DtoTokenResponse
            {
                AccessToken = encodedJwt,
                ExpiresIn = (int)_tokenProviderOptions.Expiration.TotalSeconds,
                RefreshToken = tokenEncrypted
            });
        }
Esempio n. 3
0
        public static string Decrypt(string textValue)
        {
            string        mRetVal       = "Not Authorized";
            MSecurityInfo mSecurityInfo = new MSecurityInfo(FunctionUtility.GetProfile(ConfigSettings.GetAppSettingValue("Actions_Encryption_Helper", true)), AccountUtility.CurrentProfile());

            if (mSecurityInfo.MayView)
            {
                mRetVal = CryptoUtility.Decrypt(textValue.Trim(), SecurityEntityUtility.CurrentProfile().EncryptionType, ConfigSettings.EncryptionSaltExpression);
            }
            return(mRetVal);
        }
Esempio n. 4
0
        public IHttpActionResult RequestChange(string account)
        {
            string                 mRetVal  = string.Empty;
            MAccountProfile        mProfile = AccountUtility.GetProfile(account);
            MSecurityEntityProfile mSecurityEntityProfile = SecurityEntityUtility.CurrentProfile();
            MMessageProfile        mMessageProfile        = MessageUtility.GetProfile("Request Password Reset UI");

            mRetVal = mMessageProfile.Body;
            string clearTextAccount = string.Empty;
            Logger mLog             = Logger.Instance();

            if (mProfile != null)
            {
                MAccountProfile mAccountProfile = mProfile;
                mAccountProfile.FailedAttempts = 0;
                mAccountProfile.Status         = 4;
                mAccountProfile.Password       = CryptoUtility.Encrypt(GWWebHelper.GetNewGuid, mSecurityEntityProfile.EncryptionType);
                mAccountProfile.UpdatedBy      = AccountUtility.GetProfile("anonymous").Id;
                mAccountProfile.UpdatedDate    = DateTime.Now;

                clearTextAccount = CryptoUtility.Decrypt(mProfile.Password, mSecurityEntityProfile.EncryptionType);
                try
                {
                    mMessageProfile = MessageUtility.GetProfile("RequestNewPassword");
                    MRequestNewPassword mRequestNewPassword = new MRequestNewPassword(mMessageProfile);
                    mRequestNewPassword.AccountName = HttpUtility.UrlEncode(CryptoUtility.Encrypt(mProfile.Account, mSecurityEntityProfile.EncryptionType));
                    mRequestNewPassword.FullName    = mProfile.FirstName + " " + mProfile.LastName;
                    mRequestNewPassword.Password    = HttpUtility.UrlEncode(mProfile.Password);
                    mRequestNewPassword.Server      = GWWebHelper.RootSite;
                    mProfile = AccountUtility.Save(mProfile, false, false);
                    NotifyUtility.SendMail(mRequestNewPassword, mProfile);
                    mLog.Debug("Reset password for account " + clearTextAccount);
                }
                catch (SmtpException ex)
                {
                    Exception myException = new Exception("Could not send e-mail." + ex.Message);
                    mLog.Error(myException);
                    mMessageProfile = (MMessageProfile)MessageUtility.GetProfile("PasswordSendMailError");
                    mRetVal         = mMessageProfile.Body;
                }
                catch (Exception ex)
                {
                    Exception mException = new Exception("Could not set account details." + ex.Message);
                    mLog.Error(mException);
                    mMessageProfile = (MMessageProfile)MessageUtility.GetProfile("ErrorAccountDetails");
                    mRetVal         = mMessageProfile.Body;
                }
            }
            return(Ok(mRetVal));
        }
Esempio n. 5
0
        /// <summary>
        /// Saves the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        public static void Save(MDirectoryProfile profile)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile", "profile cannot be a null reference (Nothing in Visual Basic)!");
            }
            CacheController.RemoveFromCache(s_DirectoryInfoCachedName);
            MSecurityEntityProfile mSecurityEntityProfile = SecurityEntityUtility.CurrentProfile();
            Logger mLog = Logger.Instance();

            try
            {
                profile.ImpersonatePassword = CryptoUtility.Decrypt(profile.ImpersonatePassword, mSecurityEntityProfile.EncryptionType);
            }
            catch (CryptoUtilityException)
            {
                profile.ImpersonatePassword = CryptoUtility.Encrypt(profile.ImpersonatePassword, mSecurityEntityProfile.EncryptionType);
            }
            try
            {
                profile.Directory = CryptoUtility.Decrypt(profile.Directory, mSecurityEntityProfile.EncryptionType);
            }
            catch (CryptoUtilityException)
            {
                profile.Directory = CryptoUtility.Encrypt(profile.Directory, mSecurityEntityProfile.EncryptionType);
            }
            try
            {
                profile.ImpersonateAccount = CryptoUtility.Decrypt(profile.ImpersonateAccount, mSecurityEntityProfile.EncryptionType);
            }
            catch (CryptoUtilityException)
            {
                profile.ImpersonateAccount = CryptoUtility.Encrypt(profile.ImpersonateAccount, mSecurityEntityProfile.EncryptionType);
            }
            BDirectories myBLL = new BDirectories(mSecurityEntityProfile, ConfigSettings.CentralManagement);

            try
            {
                myBLL.Save(profile);
            }
            catch (DataAccessLayerException ex)
            {
                mLog.Error(ex);
                throw new WebSupportException("Could not save the directory information!");
            }
            String mCacheName = mSecurityEntityProfile.Id.ToString(CultureInfo.CurrentCulture) + "_" + s_DirectoryInfoCachedName;

            CacheController.RemoveFromCache(mCacheName);
        }
Esempio n. 6
0
        /// <summary>
        /// Method to validate an authentication token
        /// </summary>
        /// <param name="AuthToken"></param>
        /// <param name="IPAddress"></param>
        /// <param name="UserType">type of user to be validated</param>
        /// <param name="IsAuthorize"></param>
        /// <param name="Action"></param>
        /// <returns></returns>
        public bool validateAuthToken(string AuthToken, string IPAddress, bool IsAuthorize, Enums.Action Action)
        {
            try
            {
                string AES_KEY             = CommonUtility.GetAppSettingKey(Constants.AuthToken.AES_KEY);
                string AES_SALT            = CommonUtility.GetAppSettingKey(Constants.AuthToken.AES_SALT);
                bool   IsValidateIPAddress = Convert.ToBoolean(CommonUtility.GetAppSettingKey(Constants.AuthToken.IsValidateIPAddress));
                int    TokenValiditySec    = Convert.ToInt32(CommonUtility.GetAppSettingKey(Constants.AuthToken.TokenValiditySec));

                var    TokenBody    = CryptoUtility.Decrypt(AuthToken, AES_KEY, AES_SALT);
                var    LstTokenBody = JLT.Common.Utility.StringUtility.SplitString(TokenBody, "##");
                var    LstInnerMsg  = JLT.Common.Utility.StringUtility.SplitString(LstTokenBody[0], Constants.AuthToken.SeperatorString); //InnerMsg = UserID + Role + IPAddress + CryptoUtility.GenerateTimeStamp();
                var    TokenHash    = LstTokenBody[1];
                string Msg_Hash     = string.Empty;
                using (var objTokenDBService = new TokenDBService())
                {
                    var Hash_Salt = objTokenDBService.GetHashSalt(LstInnerMsg[0]);
                    Msg_Hash = CryptoUtility.GenerateHash(LstTokenBody[0], Hash_Salt);
                }
                if (Convert.ToInt64(CryptoUtility.GenerateTimeStamp()) - Convert.ToInt64(LstInnerMsg[3]) < TokenValiditySec)
                {
                    if (IsValidateIPAddress)
                    {
                        if (!String.Equals(LstInnerMsg[2], IPAddress, StringComparison.Ordinal))
                        {
                            throw new SecurityTokenException("401|Error validating access token: Suspicious request, IP mismatch found(Token: " + AuthToken + " :: Token IP Address: " + LstInnerMsg[2] + " - Current IP Address: " + IPAddress + ")"); //Suspicious Request
                        }
                    }

                    if (String.Equals(Msg_Hash, TokenHash, StringComparison.Ordinal))
                    {
                        if (IsAuthorize)
                        {
                            if ((Convert.ToInt64(Action) & Convert.ToInt64(LstInnerMsg[1])) == Convert.ToInt64(Action))
                            {
                                return(true);
                            }
                            else
                            {
                                throw new SecurityTokenException("403|User is not authorized to perform this action(Token: " + AuthToken + " :: IP Address: " + IPAddress + ")"); //User does not have role for this action
                            }
                        }
                        else
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        throw new SecurityTokenException("401|Error validating access token: token not valid(Token: " + AuthToken + " :: IP Address: " + IPAddress + ")"); //Token Expired
                    }
                }
                else
                {
                    throw new SecurityTokenException("401|Error validating access token: Session has expired(Token: " + AuthToken + " :: IP Address: " + IPAddress + ")"); //Token Expired
                }
            }
            catch (SecurityTokenException e)
            {
                throw e;
            }
            catch (Exception ex)
            {
                throw new Exception("401|Default Exeption(Token: " + AuthToken + " | IP Address: " + IPAddress + ")", ex);
            }
        }
Esempio n. 7
0
        private void populatePage()
        {
            litSecurityEntity.Text = m_Profile.Name;
            txtSecurityEntity.Text = m_Profile.Name;
            if (m_Profile.Id == -1)
            {
                litSecurityEntity.Visible = false;
                txtSecurityEntity.Style.Add("display", "");
            }
            else
            {
                litSecurityEntity.Visible = true;
                txtSecurityEntity.Style.Add("display", "none");
            }
            txtSeqID.Text       = m_Profile.Id.ToString();
            txtDescription.Text = m_Profile.Description;
            txtURL.Text         = m_Profile.Url;
            try
            {
                txtConnectionstring.Text = CryptoUtility.Decrypt(m_Profile.ConnectionString, SecurityEntityUtility.CurrentProfile().EncryptionType);
            }
            catch (Exception)
            {
                txtConnectionstring.Text = m_Profile.ConnectionString;
            }
            litSecurityEntityTranslation.Text = ConfigSettings.SecurityEntityTranslation;
            txtAssembly_Name.Text             = m_Profile.DataAccessLayerAssemblyName;
            txtName_Space.Text = m_Profile.DataAccessLayerNamespace;
            MDirectoryProfile myDirectoryInfo = new MDirectoryProfile();
            DataView          dvSkin          = new DataView();

            dvSkin                  = FileUtility.GetDirectoryTableData(GWWebHelper.SkinPath, myDirectoryInfo, false).DefaultView;
            dvSkin.RowFilter        = "Type = 'folder'";
            dropSkin.DataSource     = dvSkin;
            dropSkin.DataTextField  = "Name";
            dropSkin.DataValueField = "Name";
            dropSkin.DataBind();

            DataView dvStyles = new DataView();

            dvStyles                  = FileUtility.GetDirectoryTableData(Server.MapPath(@"~\Content\FormStyles"), myDirectoryInfo, true).DefaultView;
            dvStyles.RowFilter        = "[Name] like '%.css'";
            dropStyles.DataSource     = dvStyles;
            dropStyles.DataTextField  = "ShortFileName";
            dropStyles.DataValueField = "ShortFileName";
            dropStyles.DataBind();
            Collection <MSecurityEntityProfile> mProfiles = SecurityEntityUtility.Profiles();

            dropParent.DataSource = mProfiles;
            MSecurityEntityProfile mm = new MSecurityEntityProfile();

            dropParent.DataTextField  = "Name";
            dropParent.DataValueField = "Id";
            dropParent.DataBind();
            ListItem lstItem = new ListItem();

            lstItem.Text  = "None";
            lstItem.Value = "-1";
            dropParent.Items.Add(lstItem);
            NameValuePairUtility.SetDropSelection(dropParent, m_Profile.ParentSeqId.ToString());
            NameValuePairUtility.SetDropSelection(dropSkin, m_Profile.Skin);
            NameValuePairUtility.SetDropSelection(dropStyles, m_Profile.Style);
            NameValuePairUtility.SetDropSelection(dropStatus, m_Profile.StatusSeqId.ToString());
            NameValuePairUtility.SetDropSelection(dropDAL, m_Profile.DataAccessLayer);
            NameValuePairUtility.SetDropSelection(dropEncryptionType, m_Profile.EncryptionType.ToString());
        }
Esempio n. 8
0
        /// <summary>
        /// Performs authentication give an account and password
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns>Boolean</returns>
        /// <remarks>
        /// Handles authentication methodology
        /// </remarks>
        public static Boolean Authenticated(String account, String password)
        {
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException("account", "account cannot be a null reference (Nothing in VB) or empty!");
            }
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException("password", "password cannot be a null reference (Nothing in VB) or empty!");
            }
            bool retVal        = false;
            bool mDomainPassed = false;

            if (account.Contains(@"\"))
            {
                mDomainPassed = true;
            }
            MAccountProfile mAccountProfile = GetProfile(account);

            if (mDomainPassed && mAccountProfile == null)
            {
                int mDomainPos = account.IndexOf(@"\", StringComparison.OrdinalIgnoreCase);
                account         = account.Substring(mDomainPos + 1, account.Length - mDomainPos - 1);
                mAccountProfile = GetProfile(account);
            }
            if (mAccountProfile != null)
            {
                if (ConfigSettings.AuthenticationType.ToUpper(CultureInfo.InvariantCulture) == "INTERNAL")
                {
                    string profilePassword = string.Empty;
                    if ((mAccountProfile != null))
                    {
                        try
                        {
                            profilePassword = CryptoUtility.Decrypt(mAccountProfile.Password, SecurityEntityUtility.CurrentProfile().EncryptionType);
                        }
                        catch (CryptoUtilityException)
                        {
                            profilePassword = mAccountProfile.Password;
                        }
                        if (password == profilePassword && (mAccountProfile.Status != Convert.ToInt32(SystemStatus.Disabled, CultureInfo.InvariantCulture) || mAccountProfile.Status != Convert.ToInt32(SystemStatus.Inactive, CultureInfo.InvariantCulture)))
                        {
                            retVal = true;
                        }
                        if (!retVal)
                        {
                            mAccountProfile.FailedAttempts += 1;
                        }
                        if (mAccountProfile.FailedAttempts == Convert.ToInt32(ConfigSettings.FailedAttempts) && Convert.ToInt32(ConfigSettings.FailedAttempts, CultureInfo.InvariantCulture) != -1)
                        {
                            mAccountProfile.Status = Convert.ToInt32(SystemStatus.Disabled, CultureInfo.InvariantCulture);
                        }
                        AccountUtility.Save(mAccountProfile, false, false);
                    }
                }
                else // LDAP authentication
                {
                    string domainAndUsername = ConfigSettings.LdapDomain + "\\" + account;
                    if (mDomainPassed)
                    {
                        domainAndUsername = account;
                    }
                    domainAndUsername = domainAndUsername.Trim();
                    DirectoryEntry entry = null;
                    object         obj   = new object();
                    try
                    {
                        entry = new DirectoryEntry(ConfigSettings.LdapServer, domainAndUsername, password);
                        //Bind to the native AdsObject to force authentication
                        //if this does not work it will throw an exception.
                        obj = entry.NativeObject;
                        mAccountProfile.LastLogOn = DateTime.Now;
                        AccountUtility.Save(mAccountProfile, false, false);
                        retVal = true;
                    }
                    catch (Exception ex)
                    {
                        string mMessage         = "Error Authenticating account " + domainAndUsername + " through LDAP.";
                        WebSupportException mEx = new WebSupportException(mMessage, ex);
                        Logger mLog             = Logger.Instance();
                        mLog.Error(mEx);
                        throw mEx;
                    }
                    finally
                    {
                        if ((obj != null))
                        {
                            obj = null;
                        }
                        if ((entry != null))
                        {
                            entry.Dispose();
                        }
                    }
                }
            }
            return(retVal);
        }
Esempio n. 9
0
        public IHttpActionResult ChangePassword(MChangePassword mChangePassword)
        {
            if (mChangePassword == null)
            {
                throw new ArgumentNullException("mChangePassword", "mChangePassword cannot be a null reference (Nothing in Visual Basic)!");
            }
            MMessageProfile        mMessageProfile        = new MMessageProfile();
            MSecurityEntityProfile mSecurityEntityProfile = SecurityEntityUtility.CurrentProfile();
            MAccountProfile        mAccountProfile        = AccountUtility.CurrentProfile();
            string mCurrentPassword = "";

            mMessageProfile = MessageUtility.GetProfile("SuccessChangePassword");
            try
            {
                mCurrentPassword = CryptoUtility.Decrypt(mAccountProfile.Password, mSecurityEntityProfile.EncryptionType);
            }
            catch (Exception)
            {
                mCurrentPassword = mAccountProfile.Password;
            }
            if (mAccountProfile.Status != (int)SystemStatus.ChangePassword)
            {
                if (mChangePassword.OldPassword != mCurrentPassword)
                {
                    mMessageProfile = MessageUtility.GetProfile("PasswordNotMatched");
                }
                else
                {
                    mAccountProfile.PasswordLastSet = System.DateTime.Now;
                    mAccountProfile.Status          = (int)SystemStatus.Active;
                    mAccountProfile.FailedAttempts  = 0;
                    mAccountProfile.Password        = CryptoUtility.Encrypt(mChangePassword.NewPassword.Trim(), mSecurityEntityProfile.EncryptionType);
                    try
                    {
                        AccountUtility.Save(mAccountProfile, false, false);
                    }
                    catch (Exception)
                    {
                        mMessageProfile = MessageUtility.GetProfile("UnSuccessChangePassword");
                    }
                }
            }
            else
            {
                try
                {
                    var _with2 = mAccountProfile;
                    _with2.PasswordLastSet = System.DateTime.Now;
                    _with2.Status          = (int)SystemStatus.Active;
                    _with2.FailedAttempts  = 0;
                    _with2.Password        = CryptoUtility.Encrypt(mChangePassword.NewPassword.Trim(), mSecurityEntityProfile.EncryptionType);
                    AccountUtility.Save(mAccountProfile, false, false);
                }
                catch (Exception)
                {
                    mMessageProfile = MessageUtility.GetProfile("UnSuccessChangePassword");
                }
            }
            AccountUtility.RemoveInMemoryInformation(true);
            return(Ok(mMessageProfile.Body));
        }