2

This will be my first question here!

Im having problems with my mvc4 app and random occurring logouts.

i use sessions to store my company id and id of the user.

        private void SetSessionData(string UserName)
    {
        Employee data = (from employee in _db.Employees where employee.Email == UserName select employee).First();
        Session.Add("Comp_ID", data.Comp_ID);
        Session.Add("Company", data.Company.Name);
        Session.Add("User_ID", data.ID);
    }

i have set the timeout value to 600 for the session (10 hours) this is even set 2 places to be sure:

        [AllowAnonymous]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            //FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); //sørger for at remember me virker!

            SetSessionData(model.UserName);
            Session.Timeout = 600;

            if (model.RememberMe)
            {
                Response.Cookies.Add(new HttpCookie("CookieUserName", model.UserName) { Expires = DateTime.Now.AddDays(30), Value = model.UserName });
                Response.Cookies.Add(new HttpCookie("CookieRememberMe", model.RememberMe.ToString()) { Expires = DateTime.Now.AddDays(30), Value = model.RememberMe.ToString() });//sætter den nye cookie
            }
            else
            {
                Response.Cookies.Set(new HttpCookie("CookieUserName") { Expires = DateTime.Now.AddDays(-1) });
                Response.Cookies.Set(new HttpCookie("CookieRememberMe") { Expires = DateTime.Now.AddDays(-1) });
            }

            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToLocal(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "Vi har enten ikke brugernavnet eller koden i kartoteket.");
        return View(model);
    }

and here in the web.config:

<system.web>
<machineKey validationKey="MyKeyGoesHere" validation="SHA1" decryption="AES" />
<sessionState timeout="600" />
<compilation debug="true" targetFramework="4.5">
  <assemblies>
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="600" />
</authentication>

My cookies seem to be saved for 10 hours, and my session_id cookie expiration seems to be set to "when the browser closes".

Server side i have set the app pool to recycle at 1am.

Even though all this is set my users still get random logouts form everything between 2 min after login to 1 hour after login.

to counter some of the random half login state problems i have had i included this:

@if(Session == null || Session["User_ID"] == null || !WebSecurity.Initialized){
                //Makes sure the session data is cleared and user logged out if session dies.
                try
                {
                    if(Session != null) {Session.Clear();}

                    if (WebSecurity.Initialized){WebSecurity.Logout();}

                    FormsAuthentication.SignOut();

                    //dette er til at stoppe cache.
                    Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.Cache.SetNoStore();

                }catch{ <p>Error Clearing Login Cache</p>}    
            }

Im pretty lost by now and hopes a guru out there might know what beginners mistake im making here!

Thanks for ALL response in advance!

Edit:

I also tried this: http://www.windowsitpro.com/article/security-development/create-persistent-id-cookies

(original link from: ASP.NET MVC FormsAuthentication Cookie timeout cannot be increased)

but that just made my app logout every single time i pressed anything after login.

The app is running on windows 2012 server with IIS8.

More adds:

I found out the session_id cookie is still set to when closed in the browser:

cloud.hviidnet.com/image/2X3v2y2e1K1S

The strange thing is its set to 600 min, even when i look in the IIS server:

cloud.hviidnet.com/image/1e3J1g2u3p2M

2
  • I've had a similar problem before; I've checked my config file and my machineKey validationKey element has a decryptionKey attribute which yours does not. you might want to remove that entire element as it may not be required if you are self hosting. see this link blog.scribz.net/2011/03/… Commented Oct 5, 2012 at 14:10
  • @wal - Thanks for your reply. The machineKey part i added because it solved a similar problem here on stackoverflow. Youre right i dont seem to have a decryptionkey. i have generated a new one that looks like this: <machineKey validationKey="57BEE8DA71A66493A7D8366B79728691F9D4E85AABFAD9AA2B4FCB05A87702100F4DEEE848525B74C7E3084AA2F38A13585B3C204A4287825D149E4F7BE34B4D" decryptionKey="E2146D73483F1028AE3C738B1100DEB0DD8BD105886DC8BF814AD19A853FF569" validation="SHA1" decryption="AES" /> I will post back if it works with the decryption tag enabled. Commented Oct 5, 2012 at 14:43

2 Answers 2

1

The solution was to remove all use of "Session." and get all the data from the database instead with WebSecurity.CurrentUserID.

Hope this helps someone else!

Sign up to request clarification or add additional context in comments.

1 Comment

Also remember to use [InitializeSimpleMembership] on all the controllers... annoying errors.
0

Do you only have a single web server? If you have multiple servers load balanced, the session could be getting lost as the user gets routed to different servers between posts, which would explain why it happens at random intervals.

1 Comment

Good idea, but it's only a single server with several sites.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.