protected void Login(object sender, EventArgs e) { System.Threading.Thread.Sleep(3000); UserModule userModule = new UserModule(); string userid = input_userid.Text; string password = input_password.Text; try { UserAccount authenticatedUser = userModule.login(userid, password); SessionIDManager sessionIdManager = new SessionIDManager(); string newId = sessionIdManager.CreateSessionID(Context); string oldUserId = ""; string oldUsername = ""; string oldUserRole = ""; if(Session["userid"] != null) oldUserId = Session["userid"].ToString(); if(Session["username"] != null) oldUsername = Session["username"].ToString(); if(Session["userRole"] != null) oldUserRole = Session["userRole"].ToString(); Session["userid"] = userid; Session["username"] = authenticatedUser.USERNAME; Session["userRole"] = authenticatedUser.ROLE; //Session["Sessionid"] = Session.SessionID; //Unnecessary if (Session["previous_url"] != null && userid.Equals(oldUserId)) //impt! potential security vulnerability { string previous_url = Session["previous_url"].ToString(); Session["previous_url"] = ""; //Clear session variable just in case Response.Redirect(previous_url); } string redirectURL = UserRoleDispatcher.getPageByUserRole(authenticatedUser.ROLE); if (redirectURL.Length <= 0) { throw new Exception("No role configured for " + authenticatedUser.ROLE + " yet, please contact administrator."); } Response.Redirect(redirectURL); } catch (LoginException lex) { login_message.Controls.Add(new LiteralControl( "<div class='alert alert-danger col-sm-10 col-sm-offset-1'>" + lex.Message + "</div>")); } catch (Exception ex) { login_message.Controls.Add(new LiteralControl( "<div class='alert alert-danger col-sm-10 col-sm-offset-1'>" + ex.Message + "</div>")); } }
void CreateNewSessionId() { SessionIDManager Manager = new SessionIDManager(); string NewID = Manager.CreateSessionID(Context); string OldID = Context.Session.SessionID; bool redirected = false; bool IsAdded = false; Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded); }
public static void ResetSessionID() { Session.Clear(); Session.Abandon(); Session.RemoveAll(); HttpContext context = HttpContext.Current; SessionIDManager manager = new SessionIDManager(); string newID = manager.CreateSessionID(context); bool redirected = false; bool isAdded = false; manager.SaveSessionID(context, newID, out redirected, out isAdded); if (null != HttpContext.Current.Request.Cookies["ASP.NET_SessionId"]) { HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = newID; } }
public HttpResponseMessage CustomerConfirmation(string email, string password) { if (string.IsNullOrEmpty(email) && string.IsNullOrEmpty(password)) { return(Request.CreateResponse(HttpStatusCode.Forbidden, "user name or password is invalid")); } if (email == "*****@*****.**" && password == "theone123456") { return(Request.CreateResponse(HttpStatusCode.OK, "This is Admin")); } else { Customer customer = m_db.Customers.SingleOrDefault(x => x.Email == email); CustomersSessions sessionNew = new CustomersSessions(); if (customer != null) { Encryption encryption = new Encryption(); if (encryption.ValidatePassword(password, customer.Password)) { SessionIDManager manager = new SessionIDManager(); string newSessionId = manager.CreateSessionID(HttpContext.Current); string CurrentTime = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second; string CurrentDate = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year; sessionNew.CustomerId = customer.Id; sessionNew.SessionId = newSessionId; sessionNew.SessionDate = CurrentDate; sessionNew.SessionTime = CurrentTime; m_db.Sessions.Add(sessionNew); m_db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, sessionNew)); } } } return(Request.CreateResponse(HttpStatusCode.Forbidden, "user name or password is invalid")); }
public static bool DeleteUser(IUserMethods userMethods, User user = null) { if (user == null) { user = UserSession.CurrentUser; } try { userMethods.RemoveUser(user); UserSession.CurrentUser = null; var session = new SessionIDManager(); session.RemoveSessionID(UserSession.CurrentContext); return(true); } catch { return(false); } }
private ISessionIDManager InitSessionIDManager(SessionStateSection config) { string sessionIdManagerType = config.SessionIDManagerType; ISessionIDManager iManager; if (string.IsNullOrEmpty(sessionIdManagerType)) { iManager = new SessionIDManager(); } else { Type managerType = Type.GetType(sessionIdManagerType, true /*throwOnError*/, false /*ignoreCase*/); CheckAssignableType(typeof(ISessionIDManager), managerType, config, "sessionIDManagerType"); iManager = (ISessionIDManager)Activator.CreateInstance(managerType); } iManager.Initialize(); return(iManager); }
public static bool Logout() { if (GetUserName() == null) { return(true); } if (HttpContext.Current == null || HttpContext.Current.Session == null) { return(true); } HttpContext.Current.Session.Abandon(); HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); SessionIDManager manager = new SessionIDManager(); manager.RemoveSessionID(HttpContext.Current); var newId = manager.CreateSessionID(HttpContext.Current); bool isRedirected; bool isAdded; manager.SaveSessionID(HttpContext.Current, newId, out isRedirected, out isAdded); return(true); }
public IHttpActionResult GetSuccessStories(CustomersSessions strSession) { SessionIDManager manager = new SessionIDManager(); CustomersSessions session = m_db.Sessions.SingleOrDefault(x => x.SessionId == strSession.SessionId); SessionController s = new SessionController(); bool isExpired = s.doesSessionExpired(strSession); if (isExpired) { manager.RemoveSessionID(HttpContext.Current); m_db.Sessions.Remove(session); m_db.SaveChanges(); return(BadRequest("Your session expierd")); } else { string newSessionTime = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second; session.SessionTime = newSessionTime; return(Ok(m_db.SuccessStories.AsEnumerable())); } }
public ActionResult Login(string username, string password, string language, string capchar) { username = username.Trim(); password = password.Trim(); var captchar = Session["Captcha"].ToString(); //if (string.IsNullOrWhiteSpace(captchar) || captchar.ToLower().Trim() != capchar.ToLower().Trim()) //{ // var rs = new // { // Status = "00", // Message = Resource.Captcharinvalid_Lang // }; // return Json(new { result = rs }, JsonRequestBehavior.AllowGet); //} System.Web.HttpContext.Current.Session.Abandon(); System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); var manager = new SessionIDManager(); manager.RemoveSessionID(System.Web.HttpContext.Current); var newId = manager.CreateSessionID(System.Web.HttpContext.Current); bool isRedirected; bool isAdded; manager.SaveSessionID(System.Web.HttpContext.Current, newId, out isRedirected, out isAdded); GetCapcharImg(); var login = new UserModel { Password = password, UserName = username.Trim(), TypeLogin = 1 }; Cache.Add(username + newId, login, DateTime.Now.AddMinutes(1)); return(RedirectToAction("Authenticate", "Login", new { username })); }
public System.Net.Http.HttpResponseMessage GetData(string controller, string action, string formToken = "") { if (FormTokenUtility.ValidateFormToken(formToken, HttpContext.Current.Session.SessionID)) { SingleActionSettingDTO setting = new SingleActionSettingDTO(new HttpRequestWrapper(HttpContext.Current.Request), base.PortalSettings.PortalId); //when calling main bpms api from client application, there is no need to pass formToken to main bpms api. string url = UrlUtility.GetApiUrl(setting.WebApiAddress, action, controller, "", this.GetParameters().ToArray()); var result = ApiUtility.GetData(url, setting.WebServicePass, base.UserInfo.Username, ApiUtility.GetIPAddress(), HttpContext.Current.Session.SessionID, FormTokenUtility.GetIsEncrypted(formToken, HttpContext.Current.Session.SessionID)); /* * In ReportEngine.cs response would be flushed and as a result sessionID will be rewrite with server * session ID which is different with singleAction sessionID because it sends data using api to server * and therefore it must rewrite sessionid there in case user call report or download a file. */ SessionIDManager Manager = new SessionIDManager(); Manager.SaveSessionID(HttpContext.Current, HttpContext.Current.Session.SessionID, out bool redirected, out bool IsAdded); return(result); } else { throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.Unauthorized); } }
protected void ProceedtoKnet_Click(object sender, EventArgs e) { if (IsPostBack) { SessionIDManager manager = new SessionIDManager(); string newID = manager.CreateSessionID(Context); //if (Session["AuthToken"] != null) //{ // log.SaveLog("RedirectToKnet", " Redirect to Knet without Auth Token ", System.Diagnostics.EventLogEntryType.Information); // Response.Redirect("genericError.html", true); //} //else //{ Session["AuthToken"] = newID; // now create a new cookie with this ID value Response.Cookies.Add(new HttpCookie("AuthToken", newID)); // Check if the same Token is being called through multiple session ????????? //} } //string EToeknId =log.ExplicitDecryptTokenCall(tokenId) ; if (paymentDataSet.Tables.Count > 0) { string sRefNo = paymentDataSet.Tables[0].Rows[0]["ReferenceNumber"].ToString(); string sRecId = paymentDataSet.Tables[0].Rows[0]["ReceiptId"].ToString(); if (sRefNo != null && sRefNo != "") { int iCheckValue = -1; String conString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; SqlConnection CheckReceiptconnection = new SqlConnection(conString); SqlCommand CheckReceiptcommand = new SqlCommand("usp_CheckForGCSKNetPaymentExpiryValidation", CheckReceiptconnection); CheckReceiptcommand.CommandType = CommandType.StoredProcedure; SqlParameter paramRefId = CheckReceiptcommand.Parameters.Add("@ReferenceNo", SqlDbType.VarChar, 30); paramRefId.Value = sRefNo; SqlParameter paramRecId = CheckReceiptcommand.Parameters.Add("@ReceiptId", SqlDbType.BigInt); paramRecId.Value = sRecId; SqlParameter paramCheck = CheckReceiptcommand.Parameters.Add("@Check", SqlDbType.Int); paramCheck.Direction = ParameterDirection.Output; paramCheck.Value = iCheckValue; CheckReceiptconnection.Open(); CheckReceiptcommand.ExecuteNonQuery(); int iCheck = (int)(CheckReceiptcommand.Parameters["@Check"].Value); CheckReceiptconnection.Close(); if (iCheck == 1) { log.SaveLog("CallPaymentGateWayGCS", "Payment Already Initiated:" + sRefNo, System.Diagnostics.EventLogEntryType.Error); AH.LoggerCall <PayReq>(activity, LogLevel.Info, null, EToeknId, "Payment Already Initiated", ErrorAt.None, null); Response.Redirect("genericPaymentError.html", true); } } if (!String.IsNullOrEmpty(paymentDataSet.Tables[0].Rows[0]["PaymentFor"].ToString())) { accountName = paymentDataSet.Tables[0].Rows[0]["PaymentFor"].ToString(); initializePaymentByAccountName(accountName); } } }
protected void btnsubmit_Click(object sender, EventArgs e) { if (txtemail.Text == "" && txtpassword.Text == "") { lblerror.Text = ""; lblemail.Text = "Email cannot be blank"; lblpassword.Text = "Password cannot be blank"; } else if (txtemail.Text != "" && txtpassword.Text == "") { lblpassword.Text = "Password cannot be blank"; txtemail.Text = ""; lblemail.Text = ""; lblerror.Text = ""; } else if (txtemail.Text == "" && txtpassword.Text != "") { txtpassword.Text = ""; lblemail.Text = "Email cannot be blank"; lblerror.Text = ""; lblpassword.Text = ""; } else if (txtemail.Text != "" && txtpassword.Text != "") { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SearchSchool_DB.mdf;Integrated Security=True"); con.Open(); lblerror.Text = ""; string emailid = Encrypt(txtemail.Text.Trim()); string pwd = Encrypt(txtpassword.Text.Trim()); SqlCommand com0 = new SqlCommand(@"Select * from Login where Emailid='" + emailid + "';", con); SqlDataReader dr0 = com0.ExecuteReader(); if (dr0.HasRows) { dr0.Read(); string istemp = dr0.GetString(8); DateTime temppwdtime = dr0.GetDateTime(9); dr0.Close(); ///if temporary password flag is set to yes and current time is less than 39 mins from when the email was sent the goto below loop if (istemp == "yes" && DateTime.Now < temppwdtime.AddMinutes(31)) { SqlCommand com = new SqlCommand(@"Select Userid,Username,Emailid,Usertype from Login where Emailid='" + emailid + "' and Temppassword ='******'", con); SqlDataReader dr = com.ExecuteReader(); if (dr.HasRows) { dr.Read(); long Userid = dr.GetInt64(0); Session["Username"] = dr.GetString(1); Session["Emailid"] = dr.GetString(2); SessionIDManager Manager = new SessionIDManager(); string NewID = Manager.CreateSessionID(Context); string OldID = Context.Session.SessionID; string ip = HttpContext.Current.Request.UserHostAddress; string username = dr.GetString(1); DateTime time = DateTime.Now; // Use current time string format = "yyyy-MM-dd HH:mm:ss"; dr.Close(); SqlCommand cmd0 = new SqlCommand(cmdText: @"insert into SessionMaster(SessionId,Username,Ipaddress,Logintime,Logouttime) values('" + NewID.ToString() + "','" + username + "','" + ip + "','" + time.ToString(format) + "','" + time.ToString(format) + "')", connection: con); cmd0.ExecuteNonQuery(); Response.Redirect("Changepassword.aspx?sess=" + NewID); } else { lblerror.Text = "Temp Password:Please enter valid email and password!"; lblemail.Text = ""; lblpassword.Text = ""; txtemail.Text = ""; txtpassword.Text = ""; } dr.Close(); } else if (istemp == "yes" && DateTime.Now > temppwdtime.AddMinutes(31)) { lblerror.Text = "Temporary password has expired. Kindly Re-Generate again using forgot password"; } else if (istemp == "no") { SqlCommand com = new SqlCommand(@"Select Userid,Username,Usertype from Login where Emailid='" + emailid + "' and Password ='******'", con); SqlDataReader dr1 = com.ExecuteReader(); if (dr1.HasRows) { dr1.Read(); long Userid = dr1.GetInt64(0); Session["Username"] = dr1.GetString(1); SessionIDManager Manager = new SessionIDManager(); string NewID = Manager.CreateSessionID(Context); string OldID = Context.Session.SessionID; string ip = HttpContext.Current.Request.UserHostAddress; string username = dr1.GetString(1); DateTime time = DateTime.Now; // Use current time string format = "yyyy-MM-dd HH:mm:ss"; dr1.Close(); SqlCommand cmd0 = new SqlCommand(cmdText: @"insert into SessionMaster(SessionId,Username,Ipaddress,Logintime,Logouttime) values('" + NewID.ToString() + "','" + username + "','" + ip + "','" + time.ToString(format) + "','" + time.ToString(format) + "')", connection: con); cmd0.ExecuteNonQuery(); Response.Redirect("Homepageuser.aspx?sess=" + NewID); } else { lblerror.Text = "Actual Password: Please enter valid email and password!"; lblemail.Text = ""; lblpassword.Text = ""; txtemail.Text = ""; txtpassword.Text = ""; } } } else { con.Close(); lblerror.Text = "Please enter valid email and password!"; lblemail.Text = ""; lblpassword.Text = ""; txtemail.Text = ""; txtpassword.Text = ""; } } }
protected void lnkloginStatus_Click(object sender, EventArgs e) { try { SageFrameConfig SageConfig = new SageFrameConfig(); SageFrameSettingKeys.PageExtension = SageConfig.GetSettingsByKey(SageFrameSettingKeys.SettingPageExtension); bool EnableSessionTracker = bool.Parse(SageConfig.GetSettingsByKey(SageFrameSettingKeys.EnableSessionTracker)); SessionTracker sessionTrackerNew = new SessionTracker(); if (EnableSessionTracker) { string sessionID = HttpContext.Current.Session.SessionID; SageFrame.Web.SessionLog sLogNew = new SageFrame.Web.SessionLog(); sLogNew.SessionLogStart(sessionTrackerNew, sessionID); } string ReturnUrl = string.Empty; string RedUrl = string.Empty; SageFrameConfig sfConfig = new SageFrameConfig(); if (lnkloginStatus.CommandName == "LOGIN") { if (Request.QueryString["ReturnUrl"] == null) { ReturnUrl = Request.RawUrl.ToString(); if (!(ReturnUrl.ToLower().Contains(SageFrameSettingKeys.PageExtension))) { //ReturnUrl = ReturnUrl.Remove(strURL.LastIndexOf('/')); if (ReturnUrl.EndsWith("/")) { ReturnUrl += sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } else { ReturnUrl += '/' + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } } } else { ReturnUrl = Request.QueryString["ReturnUrl"].ToString(); } if (!IsParent) { RedUrl = GetParentURL + "/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalLoginpage) + SageFrameSettingKeys.PageExtension; } else { RedUrl = GetParentURL + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalLoginpage) + SageFrameSettingKeys.PageExtension; } } else { if (EnableSessionTracker) { SageFrame.Web.SessionLog sLog = new SageFrame.Web.SessionLog(); sLog.SessionLogEnd(GetPortalID); } SecurityPolicy objSecurity = new SecurityPolicy(); HttpCookie authenticateCookie = new HttpCookie(objSecurity.FormsCookieName(GetPortalID)); authenticateCookie.Expires = DateTime.Now.AddYears(-1); string randomCookieValue = GenerateRandomCookieValue(); HttpContext.Current.Session[SessionKeys.RandomCookieValue] = randomCookieValue; Response.Cookies.Add(authenticateCookie); lnkloginStatus.Text = "Login"; SetUserRoles(string.Empty); //create new sessionID SessionIDManager manager = new SessionIDManager(); manager.RemoveSessionID(System.Web.HttpContext.Current); var newId = manager.CreateSessionID(System.Web.HttpContext.Current); var isRedirected = true; var isAdded = true; manager.SaveSessionID(System.Web.HttpContext.Current, newId, out isRedirected, out isAdded); if (!IsParent) { RedUrl = GetParentURL + "/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } else { RedUrl = GetParentURL + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } } CheckOutHelper cHelper = new CheckOutHelper(); cHelper.ClearSessions(); FormsAuthentication.SignOut(); Response.Redirect(RedUrl, false); } catch (Exception ex) { ProcessException(ex); } }
/// <summary> /// set the ID of the current http session /// </summary> /// <param name="id">session ID</param> /// <returns></returns> public static void SetSessionId(string id) { var manager = new SessionIDManager(); manager.SaveSessionID(HttpContext.Current, id, out bool redirected, out bool cookieAdded); }
protected void btnsignup_Click(object sender, EventArgs e) { if (txtuname.Text == "" && txtemail.Text == "" && txtpassword.Text == "") { lblerror.Text = ""; lbluname.Text = "Username cannot be blank"; lblemail.Text = "Email cannot be blank"; lblpassword.Text = "Email cannot be blank"; } else if (txtuname.Text != "" && txtemail.Text == "" && txtpassword.Text == "") { lblerror.Text = ""; lblemail.Text = "Email cannot be blank"; lblpassword.Text = "Email cannot be blank"; } else if (txtuname.Text == "" && txtemail.Text != "" && txtpassword.Text == "") { lblerror.Text = ""; lbluname.Text = "Username cannot be blank"; lblpassword.Text = "Email cannot be blank"; } else if (txtuname.Text == "" && txtemail.Text == "" && txtpassword.Text != "") { lblerror.Text = ""; lbluname.Text = "Username cannot be blank"; lblemail.Text = "Email cannot be blank"; } else if (txtuname.Text != "" && txtemail.Text != "" && txtpassword.Text != "") { string emailid = Encrypt(txtemail.Text.Trim().ToLower()); con.Open(); SqlCommand cmd0 = new SqlCommand("Select Emailid from Login where Emailid ='" + emailid + "';", con); SqlDataReader dr = cmd0.ExecuteReader(); if (dr.HasRows) { dr.Read(); string email = dr.GetString(0); if (emailid == email) { lblerror.Text = "The email you have entered already exists!!"; txtuname.Text = ""; txtemail.Text = ""; txtpassword.Text = ""; } } else { dr.Close(); //con.Close(); //try //{ //string email = Encrypt(txtemail.Text.Trim().ToLower()); string email = Encrypt(txtemail.Text.Trim()); string uname = txtuname.Text.Trim(); string password = Encrypt(txtpassword.Text.Trim()); DateTime time = DateTime.Now; // Use current time string format = "yyyy-MM-dd HH:mm:ss"; //con.Open(); SqlCommand cmdr = new SqlCommand("Insert into Login values('" + uname + "','" + email + "','" + password + "','User','" + time.ToString(format) + "','" + time.ToString(format) + "','NULL','no','01-01-1990 12:00:00');", con); cmdr.ExecuteNonQuery(); string display = "User registered successfully!"; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true); Session["Username"] = uname; Session["UseIsAuthenticated"] = "true"; SessionIDManager Manager = new SessionIDManager(); string NewID = Manager.CreateSessionID(Context); string OldID = Context.Session.SessionID; string ip = HttpContext.Current.Request.UserHostAddress; //SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SearchSchool_DB.mdf;Integrated Security=True"); //con.Open(); SqlCommand cmd2 = new SqlCommand(cmdText: "insert into SessionMaster(SessionId,Username,Ipaddress,Logintime,Logouttime) values('" + NewID.ToString() + "','" + uname + "','" + ip + "','" + time.ToString(format) + "','" + time.ToString(format) + "')", connection: con); cmd2.ExecuteNonQuery(); Response.Redirect("Homepageuser.aspx?sess=" + NewID); //Response.AppendHeader("Refresh", "2;url=Homepageuser.aspx?sess=" + NewID); //txtemail.Text = ""; //txtpassword.Text = ""; //txtuname.Text = ""; //lblerror.Text = ""; //lblemail.Text = ""; //lblpassword.Text = ""; //lbluname.Text = ""; //SqlCommand com = new SqlCommand(@"Select Userid,Username,Usertype from Login where Emailid='" + emailid + "' and Password ='******'", con); //SqlDataReader dr1 = com.ExecuteReader(); //if (dr1.HasRows) //{ // dr1.Read(); // long Userid = dr1.GetInt64(0); // Session["UseIsAuthenticated"] = "true"; // Response.AppendHeader("Refresh", "5;url=Homepageuser.aspx?Userid=" + Userid); //} con.Close(); //} //catch (Exception ex) //{ // ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true); //} } } }
public void CreateNewSession() { SessionId = new SessionIDManager().CreateSessionID(null); _httpContext.ResponseCookies[AspNetSessionCookieName] = SessionId; }
// adapted from https://stackoverflow.com/a/4420114/6121074 /// <summary> /// prevent http session fixation attack by generating a new http session ID upon login /// </summary> /// <remarks> /// https://www.owasp.org/index.php/Session_Fixation /// </remarks> /// <returns>new session ID</returns> public static string RegenerateSessionId() { // create a new session id var manager = new SessionIDManager(); var oldId = manager.GetSessionID(HttpContext.Current); var newId = manager.CreateSessionID(HttpContext.Current); bool redirected, cookieAdded; manager.SaveSessionID(HttpContext.Current, newId, out redirected, out cookieAdded); // retrieve the current session var application = HttpContext.Current.ApplicationInstance; var session = (SessionStateModule)application.Modules.Get("Session"); var fields = session.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); // parse the session fields SessionStateStoreProviderBase store = null; FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null; SessionStateStoreData rqItem = null; foreach (var field in fields) { switch (field.Name) { case "_store": store = (SessionStateStoreProviderBase)field.GetValue(session); break; case "_rqId": rqIdField = field; break; case "_rqLockId": rqLockIdField = field; break; case "_rqSessionStateNotFound": rqStateNotFoundField = field; break; case "_rqItem": rqItem = (SessionStateStoreData)field.GetValue(session); break; } } // remove the session from the store var lockId = rqLockIdField.GetValue(session); if (lockId != null && oldId != null) { store.RemoveItem(HttpContext.Current, oldId, lockId, rqItem); } // assign the new id to the session // the session will be added back to the store, with the new id, on the next http request rqStateNotFoundField.SetValue(session, true); rqIdField.SetValue(session, newId); return(newId); }
protected void lnkloginStatus_Click(object sender, EventArgs e) { try { SageFrameConfig SageConfig = new SageFrameConfig(); SageFrameSettingKeys.PageExtension = SageConfig.GetSettingsByKey(SageFrameSettingKeys.SettingPageExtension); bool EnableSessionTracker = bool.Parse(SageConfig.GetSettingsByKey(SageFrameSettingKeys.EnableSessionTracker)); SessionTracker sessionTrackerNew = new SessionTracker(); if (EnableSessionTracker) { string sessionID = HttpContext.Current.Session.SessionID; SageFrame.Web.SessionLog sLogNew = new SageFrame.Web.SessionLog(); sLogNew.SessionLogStart(sessionTrackerNew, sessionID); } string ReturnUrl = string.Empty; string RedUrl = string.Empty; SageFrameConfig sfConfig = new SageFrameConfig(); if (lnkloginStatus.CommandName == "LOGIN") { if (Request.QueryString["ReturnUrl"] == null) { ReturnUrl = Request.RawUrl.ToString(); if (!(ReturnUrl.ToLower().Contains(SageFrameSettingKeys.PageExtension))) { //ReturnUrl = ReturnUrl.Remove(strURL.LastIndexOf('/')); if (ReturnUrl.EndsWith("/")) { ReturnUrl += sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } else { ReturnUrl += '/' + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } } } else { ReturnUrl = Request.QueryString["ReturnUrl"].ToString(); } if (!IsParent) { RedUrl = GetParentURL + "/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalLoginpage) + SageFrameSettingKeys.PageExtension; } else { RedUrl = GetParentURL + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalLoginpage) + SageFrameSettingKeys.PageExtension; } } else { if (EnableSessionTracker) { SageFrame.Web.SessionLog sLog = new SageFrame.Web.SessionLog(); sLog.SessionLogEnd(GetPortalID); } SecurityPolicy objSecurity = new SecurityPolicy(); HttpCookie authenticateCookie = new HttpCookie(objSecurity.FormsCookieName(GetPortalID)); authenticateCookie.Expires = DateTime.Now.AddYears(-1); string randomCookieValue = GenerateRandomCookieValue(); HttpContext.Current.Session[SessionKeys.RandomCookieValue] = randomCookieValue; Response.Cookies.Add(authenticateCookie); lnkloginStatus.Text = "Login"; SetUserRoles(string.Empty); //create new sessionID SessionIDManager manager = new SessionIDManager(); manager.RemoveSessionID(System.Web.HttpContext.Current); var newId = manager.CreateSessionID(System.Web.HttpContext.Current); var isRedirected = true; var isAdded = true; manager.SaveSessionID(System.Web.HttpContext.Current, newId, out isRedirected, out isAdded); if (!IsParent) { RedUrl = GetParentURL + "/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } else { RedUrl = GetParentURL + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + SageFrameSettingKeys.PageExtension; } } CheckOutHelper cHelper = new CheckOutHelper(); cHelper.ClearSessions(); FormsAuthentication.SignOut(); Response.Redirect(RedUrl, false); } catch (Exception ex) { ProcessException(ex); } }
public MyCsvSessionIDManager() { this.manager = new SessionIDManager(); }
/// <summary> /// Called before the action method is invoked. /// </summary> /// <param name="filterContext">Information about the current request and action.</param> /// <exception cref="System.Exception"> /// </exception> protected override void OnActionExecuting(ActionExecutingContext filterContext) { // get SessionId from queryString string sessionId = filterContext.RequestContext.HttpContext.Request["SessionId"]; if (!string.IsNullOrWhiteSpace(sessionId)) { var manager = new SessionIDManager(); bool redirected, isAdded; manager.SaveSessionID(System.Web.HttpContext.Current, sessionId, out redirected, out isAdded); } string currentScreenId = (string)ViewBag.CoreCenter_ScreenID; string screenType = string.Empty; this.CmnEntityModel.CurrentScreenID = currentScreenId; if (string.IsNullOrEmpty(this.cmnEntityModel.UserName) && (currentScreenId != "DCW001" && currentScreenId != "DCW002")) { throw new Exception("GLV_SYS_LoginException"); } this._ShowModelStateError(); // Reset error this.CmnEntityModel.ErrorMsgCd = string.Empty; this.CmnEntityModel.ErrorMsgReplaceString = string.Empty; // Get TabId POST/GET if (filterContext.HttpContext.Request.HttpMethod == HttpMethod.Post.Method) { this.tabId = filterContext.HttpContext.Request.Form["hfldUniqueTabSession"]; } else { this.tabId = filterContext.HttpContext.Request.QueryString["tabId"]; } // Get TabId in AJAX Request if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) { string jsonPost = string.Empty; filterContext.HttpContext.Request.InputStream.Position = 0; using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream)) { jsonPost = reader.ReadToEnd(); } if (!string.IsNullOrEmpty(jsonPost)) { var jsonPostData = Newtonsoft.Json.JsonConvert.DeserializeObject <IDictionary <string, object> >(jsonPost); this.tabId = (jsonPostData != null && jsonPostData.ContainsKey("hfldUniqueTabSession") && jsonPostData["hfldUniqueTabSession"] != null) ? Convert.ToString(jsonPostData["hfldUniqueTabSession"]) : ""; } } //if (string.IsNullOrEmpty( this.tabId )) //{ // return; //} // Save TabId and Screen Route this.cmnTabEntityModel = this.GetCmnTabEntityModel(this.tabId); this.cmnTabEntityModel.TabID = this.tabId; this.cmnTabEntityModel.CurrentScreenID = currentScreenId; if (this.cmnTabEntityModel.CurrentScreenID.Equals("DCW001")) { this.cmnTabEntityModel.ScreenRoute = string.Empty; } else if (this.cmnTabEntityModel.CurrentScreenID.Equals("DCW002")) { this.cmnTabEntityModel.ScreenRoute = "DCW002"; } else if (!this.cmnTabEntityModel.ScreenRoute.Contains(currentScreenId)) { if (string.IsNullOrEmpty(this.cmnTabEntityModel.ScreenRoute)) { this.cmnTabEntityModel.ScreenRoute = currentScreenId; } else { this.cmnTabEntityModel.ScreenRoute += "," + currentScreenId; } } string[] screenList = this.cmnTabEntityModel.ScreenRoute.Split(','); if (screenList.Length > 1) { this.cmnTabEntityModel.ParrentScreenID = screenList[screenList.Length - 2]; } this.SaveCache("CmnTabEntityModel", this.cmnTabEntityModel); #region "Back" if (Request.UrlReferrer != null) { string currentScreenID = UriUtility.GetScreenIDFromURL(Request.Url.AbsoluteUri); string referrerScreenID = UriUtility.GetScreenIDFromURL(Request.UrlReferrer.AbsoluteUri); if (currentScreenID != referrerScreenID && !Request.Url.AbsoluteUri.Contains("IsBack")) { this.SaveCache(currentScreenID + ".BackURL", Request.UrlReferrer.AbsoluteUri); } } #endregion #region Detecting Refresh var cookie = this.GetCache <string>("UrlCheckRefresh"); this.cmnTabEntityModel.IsRefreshed = filterContext.HttpContext.Request.Url != null && (cookie != null && cookie == filterContext.HttpContext.Request.Url.ToString()); #endregion #region Current screen Id for common CacheUtil.SaveCache("_CommonCurrentScreenId", currentScreenId); #endregion CacheUtil.SaveCache(CacheKeys.CmnEntityModel, cmnEntityModel); }
protected void LoginStatus1_LoggedOut(object sender, EventArgs e) { SetUserRoles(string.Empty); SageFrameConfig sageConfig = new SageFrameConfig(); //create new sessionID SessionIDManager manager = new SessionIDManager(); manager.RemoveSessionID(System.Web.HttpContext.Current); var newId = manager.CreateSessionID(System.Web.HttpContext.Current); var isRedirected = true; var isAdded = true; manager.SaveSessionID(System.Web.HttpContext.Current, newId, out isRedirected, out isAdded); Session.Remove("Auth_Token"); //Catch activity log if (!IsParent) { Response.Redirect(GetParentURL + "/portal/" + GetPortalSEOName + "/" + sageConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + Extension); } else { Response.Redirect(GetParentURL + "/" + sageConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + Extension); } }
/// <summary> /// create a new ID for the current http session /// </summary> /// <returns>new session ID</returns> public static string CreateSessionId() { var manager = new SessionIDManager(); return(manager.CreateSessionID(HttpContext.Current)); }
public ActionResult LoginToken(TokenViewModel viewModel) { try { if (ModelState.IsValid) { User user = userRepository.GetUserByUsername(viewModel.Username); if (user != null) { if (HashHelper.CompareStringWithHash(viewModel.Password, user.Password)) { var token = tokenRepository.GetTokenValid(viewModel.Token, user.Id); if (token != null) { try { // Mark token as deleted userRepository.AddUserLog(user.Id, "Logged in successful"); token.DeletedOn = DateTime.Now; db.SaveChanges(); // Create Session Session[ConstHelper.SessionDefaultName] = user.Id; // Add to db userRepository.CreateUserLogInForUserId(user.Id, Request.UserHostAddress, Session.SessionID); SessionIDManager sessionIdManager = new SessionIDManager(); string sessionId = sessionIdManager.CreateSessionID(System.Web.HttpContext.Current); // Redirect authenticated user if (user.Role == ((int)(UserRole.Admin)).ToString()) { return(RedirectToAction("Dashboard", "Admin")); } if (user.Role == ((int)(UserRole.User)).ToString()) { return(RedirectToAction("Dashboard", "User")); } } catch (Exception ex) { userRepository.AddUserLog(user.Id, "Login Failed with error" + ex.Message); ViewBag.ErrorMessage = "Technical Errors occured"; return(View()); } } else { ViewBag.ErrorMessage = "Token invalid, Try again!"; return(View("LoginToken", viewModel)); } } else { ViewBag.ErrorMessage = "Pssword invalid"; return(RedirectToAction("Login")); } } else { viewModel.Username = ""; ViewBag.ErrorMessage = "User doesn't exist"; return(RedirectToAction("Login")); } } else { ViewBag.ErrorMessage = "Please fill all fields"; return(RedirectToAction("Login")); } return(View("LoginToken", viewModel)); } catch (Exception ex) { userRepository.AddUserLog(null, "Login Failed with error" + ex.Message); ViewBag.ErrorMessage = "Technical Errors occured"; return(View()); } }
public static (bool password, bool verified) Login(string usernameEmail, string password) { User user = null; var verified = true; var vPassword = true; if (_userMethods.UserExists(usernameEmail)) { user = (User)_userMethods.GetUserByUsername(usernameEmail); } else if (_userMethods.EmailExists(usernameEmail)) { user = (User)_userMethods.GetUserByEmail(usernameEmail); } else { vPassword = false; } if (!vPassword) { return(vPassword, verified); } if (!user.Verified) { verified = false; } vPassword = user.Password == UserValidation.HashText(password, user.Salt, new SHA512CryptoServiceProvider()); if (vPassword && verified) { var manager = new SessionIDManager(); bool redirected; bool isAdded; var oldID = UserSession.CurrentContext.Session.SessionID; var id = manager.CreateSessionID(UserSession.CurrentContext); UserSession.CurrentUser = user; var oldDate = user.LastLogin; user.LastLogin = DateTime.UtcNow; _userMethods.UpdateUser(user); user.LastLogin = oldDate; UserSession.AddTempSession(id, UserSession.CurrentContext.Session); manager.RemoveSessionID(UserSession.CurrentContext); manager.SaveSessionID(UserSession.CurrentContext, id, out redirected, out isAdded); for (var i = 0; i < UserSession.CurrentContext.Response.Cookies.Count; i++) { var cookie = UserSession.CurrentContext.Response.Cookies.Get(i); if (cookie != null && cookie.Value == id) { var current = cookie; current.Expires = DateTime.Now.AddMonths(2); UserSession.CurrentContext.Response.Cookies.Remove(current.Name); UserSession.CurrentContext.Response.Cookies.Add(current); } } } return(vPassword, verified); }
public static String createSessionID() { SessionIDManager manager = new SessionIDManager(); return(manager.CreateSessionID(System.Web.HttpContext.Current)); }