Login as… best practices?

2019-06-05 06:36发布

问题:

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:

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;
    }