1
votes

I'm developing a site where an admin user will be able to login as other user types in the system. I there for have a need to track a current "display" user and the current "logged in" user. The most obvious place seems to be session but then you have challenges keeping the session timeout in sync with the authentication timeout.

See my question here: MVC session expiring but not authentication

What are the best practices for handling this kind of a scenario?

1
If you don't want to use sessions then I would database it.user1477388
I'm eager to know if/how you have solved the problem since I'm in a similar situation and don't know how to implement it. Thanksmrmashal
I believe that I used session for the solution here, though you can also use the token based technique usually reserved for REST APIs (I usually use JWT jwt.io), stored in a cookie. The JWT token is safe to rely on because it includes a checksum to ensure that the data isn't tampered withJosh Russo

1 Answers

0
votes

Besides the usual web.config settings for timeouts/security:

<location path="Portal/Dashboard">
<system.web>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>
</location>

<authentication mode="Forms">
  <forms loginUrl="~/Portal/Logout" timeout="10" />
</authentication>

Here's how I handle this in my controllers:

        loggedInPlayer = (Player)Session["currentPlayer"];
        if (loggedInPlayer == null)
        {
            loggedInPlayer = Common.readCookieData(User.Identity);
        }
        if (loggedInPlayer.UserID > 0)
        {
          //Dude's signed in, do work here
        }
     else
        {
            return PartialView("Logout");
        }

And then for my LogOut() controller method I say:

public ActionResult Logout()
    {
        Session["currentPlayer"] = null;
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home", new { l = "1"}); //Your login page
    }

For processing cookies I have:

public static Player readCookieData(System.Security.Principal.IIdentity x)
    {
        Player loggedInPlayer = new Player();
        if (x.IsAuthenticated)
        {
            loggedInPlayer.UserID = 0;
            if (x is FormsIdentity)
            {
                FormsIdentity identity = (FormsIdentity)x;
                FormsAuthenticationTicket ticket = identity.Ticket;
                string[] ticketData = ticket.UserData.Split('|');
                loggedInPlayer.UserID = Convert.ToInt32(ticketData[0]);
                loggedInPlayer.UserFName = ticketData[1];
                loggedInPlayer.UserLName = ticketData[2];
            }
        }
        else
        {
            loggedInPlayer.UserID = 0;
            loggedInPlayer.UserFName = "?";
            loggedInPlayer.UserLName = "?";
        }
        return loggedInPlayer;
    }