Link to home
Create AccountLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

Session variable was carried over from one browser to the second one

I have an ASP.Net and this is what happened on the same computer:

1. I query the database and save officeId in a session variable. Example OfficeId = 6
2. I use this thru out the site
3. User needs to click on logout button and I clear the session
4. User did NOT click on the logout and x-ed out
5. User opened a second browser and logged in with a user who's officeId is 1768
6. User added some data but this data was saved as OfficeId = 6 not as officeid 1768
7. Session is set to 20 mins in web config
8. I dont save the session in database since this is just one field I keep in session.

What do I need to do? Anyway to disable the x in browser (doubt it), Should I clear the session on first page load and reload it from database, should I be using Cache object and not session?

Thanks
SOLUTION
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
This is a bug with the code - session variables do not transfer between sessions.

When you say 'second browser', was it the same as the first i.e. IE, and had all instances of the browser been closed in-between?

Anyway if they logged in you would have stored the new value over the old value (if by some chance the old value existed).

If you can reproduce it, step-through the code that is loggin in, and then saving to the database to determine why the value is incorrect.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of Camillia

ASKER

ok, let me try to recreate it.

>>When you say 'second browser', was it the same as the first i.e. IE, and had all instances of the browser been closed in-between?

The user who did this reported that she closed the first browser (x-out) and opened a new one and logged in with a new login. I look at the database. The row she created has the login's id (ex: joe) in "userupdate" but the OfficeId is wrong.  I think she used IE as both browsers.
I asked her and this is what she did :

 1. She logged in as an administrator (this has officeid = 6). She got the other person's username/pwd by logging in as admin.

 2. she opened a second browser and entered in his username and password then she closed the admin browser after he logged in (this person's office id is NOT 6). The data he created was saved under office Id = 6

Let me see if i can reacreate. Not sure how office Id's session of 6 carried over to the second browser.
yeah, i cant recreate. I thought since the session is set for 20 mins and 2 browsers for 2 different offices were open..somehow the session from first browser stayed active and second browser picked it up! not sure how this happened
Ar, that might explain it. Most browsers these days run as a single instance, even though there might be multiple tabs and/or instances running. So if you open a second window while the first is still open, the second window gains all the session data from the first.

However the fact that she attempted to login in the second window probably means something is wrong with the login code, because a new login should overwrite the existing login data *unless* your login code checks to see if the person is already logged in and if so ignores the second attempt?
>> because a new login should overwrite the existing login data *unless* your login code checks to see if the person is already logged in and if so ignores the second attempt?

No, I dont check if the person is already logged in. This is my login code. I use Forms authentication. (sorry for posting the entire code, kinda long)

webconfig

 <authentication mode="Forms">
      <forms loginUrl="Default.aspx" defaultUrl="~/Main/Dashboard/Incoming.aspx?pageTitleId=15" timeout="2880"/>
    </authentication>

Open in new window



This is the default.aspx page. It's that Session["BusinessId"] that had the wrong value. For the second user, it should've got the Id of 1768 but still had Id of 6 which is the administrator's site.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.layouttemplate.aspx

        System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddYears(-1));
        System.Web.HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        System.Web.HttpContext.Current.Response.Cache.SetNoStore();
        System.Web.HttpContext.Current.Response.Cache.SetNoServerCaching();
        System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        ////http://forums.asp.net/t/1013531.aspx/1
        //Response.ClearHeaders();
        //Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 
        //Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 
        //Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 
        //Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 
        //Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1  
        //Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1  
        //Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1  
        //Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1  
        //Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1  
        //Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1 

        FindButton(Login1); //done in javascript now
        Login1.Focus();

        //if (!string.IsNullOrEmpty(Login1.Password) && !string.IsNullOrEmpty(Login1.UserName))
        //{
        //    AuthenticateEventArgs auth = new AuthenticateEventArgs();
        //    auth.Authenticated = true;
        //    OnAuthenticate(this, auth);
        //}


    }

    public void FindButton(Control c)
    {//focus on submit button
        foreach (Control b in c.Controls)
        {
            if (b is LinkButton)
            {
                b.Focus();
                frm.DefaultButton = b.UniqueID;
                return;


            }
            if (b.HasControls())
            {
                FindButton(b);
            }
        }
    }



    private bool SiteSpecificAuthenticationMethod(string userName, string password)
    {
        //get businessId based on login name 
        Literal lmsg = (Literal)Login1.FindControl("lmsg");

        try
        {
            if (string.IsNullOrEmpty(Login1.UserName) || string.IsNullOrEmpty(Login1.Password))
            {
                lmsg.Text = "<font style='font-size:11px; color:#ff0000'>Username & Password are required.</font>";
                return false;
            }
            if (Membership.GetUser(Login1.UserName) != null)
            {
                bool LockStatus = Membership.GetUser(Login1.UserName).IsLockedOut;
                if (LockStatus)
                {
                    lmsg.Text = "<font style='font-size:11px; color:#ff0000'>Your account is locked.</font>";
                    return false;
                }
            }

            if (Membership.ValidateUser(Login1.UserName, Login1.Password))
            {

                Session["username"] = Login1.UserName;
                ProfileData pd = new ProfileData();

                foreach (var row in pd.LoadOfficeUserNameDetail(Login1.UserName))
                {
                    Session["BusinessId"] = row.BusinessNameId;
                    if (string.IsNullOrEmpty(row.FirstTimeLogin.ToString()))
                        ViewState["FirstTimeLogin"] = "0";
                    ViewState["OfficeManager"] = row.SignedUserType;
                }
            }

            else
            {
                //Login1.FailureText = "<font style='font-size:11px; color:#ff0000'>Invalid Username or Password.</font>";
                lmsg.Text = "<font style='font-size:11px; color:#ff0000'>Invalid Username or Password.</font>";
                return false;
            }
        }
        catch (Exception ex)
        {
            ErrorLog el = new ErrorLog
            {
                UserName = Login1.UserName,
                PageName = "Login Page",
                ErrorMsg = ex.Message,
                UpdateDate = DateTime.Now
            };

            new LogAction().LogError(el);
            Session.Abandon();
            return false;


        }
        return true;
    }


    public void OnAuthenticate(object sender, AuthenticateEventArgs e)
    {
        bool authenticated = false;
        authenticated = SiteSpecificAuthenticationMethod(Login1.UserName, Login1.Password);

        e.Authenticated = authenticated;


        // if user is Admin (type 3 or 1), has access to profile section. If user is Staff, doesnt need the Complete profile page.
        //Staff should be promoted to change their password only
        // so, check for role
        if (ViewState["FirstTimeLogin"] != null)
            if (authenticated && ViewState["FirstTimeLogin"].ToString() == "0" && ViewState["OfficeManager"].ToString() == "3" && Roles.IsUserInRole(Login1.UserName, "Admin"))
                Login1.DestinationPageUrl = "~/main/profile/InitialSignup.aspx?pageTitleId=50";
            else if (authenticated && ViewState["FirstTimeLogin"].ToString() == "0" && (Roles.IsUserInRole(Login1.UserName, "Staff") || Roles.IsUserInRole(Login1.UserName, "Admin")))
                Login1.DestinationPageUrl = "~/main/UserAccess/ChangePassword.aspx?pageTitleId=35&FirstTime=Y";

    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
let me try
I'll keep testing this and I'll clear the session, just in case.