1

我正在开发一个站点,管理员用户将能够以系统中其他用户类型的身份登录。我在那里需要跟踪当前的“显示”用户和当前的“登录”用户。最明显的地方似乎是会话,但您面临保持会话超时与身份验证超时同步的挑战。

在这里查看我的问题: MVC session expiring but not authentication

处理这种情况的最佳实践是什么?

4

1 回答 1

0

除了通常的 web.config 超时/安全设置:

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

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

这是我在控制器中处理此问题的方法:

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

然后对于我的 LogOut() 控制器方法,我说:

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

对于处理 cookie,我有:

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;
    }
于 2012-09-05T22:57:36.243 回答