【问题标题】:MVC session expiring but not authenticationMVC 会话到期但未进行身份验证
【发布时间】:2012-08-29 16:53:47
【问题描述】:

我正在开发 C# MVC 应用程序,但我似乎无法同步身份验证和会话超时。我有一个基本的表单身份验证设置和一些有限的会话值。我将身份验证超时设置为小于会话(28 分钟对 30 分钟),但针对开发 Web 服务器运行,会话将在服务器重新启动时被擦除,但身份验证仍然存在。我假设身份验证存储在一个显然在服务器重启后仍然存在的 cookie 中。

<authentication mode="Forms" >
  <forms loginUrl="~/Account/Login" timeout="28" />
</authentication>
<sessionState timeout="30" />

如果 Session 为空,我想我想强制身份验证超时,然后强制登录。

那是我真正想做的吗?如果是这样,我该如何以及在哪里执行此操作?

如果没有,处理这个问题的正确方法是什么?

编辑

为了更多的观点,我还为同一个项目发布了这个问题:Login as... best practices?

【问题讨论】:

  • 您可以将会话存储在 SQL 服务器中,这样会话将持续存在。
  • 更好的方法是以与会话无关的方式编写您的应用程序,而不是依赖会话来产生影响。

标签: asp.net-mvc forms-authentication session-timeout


【解决方案1】:

我找到了答案。覆盖授权属性。这似乎是最优雅的方法:

public class AuthorizeWithSessionAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session == null || httpContext.Session["CurrentUser"] == null)
            return false;

        return base.AuthorizeCore(httpContext);
    }

}

【讨论】:

    【解决方案2】:

    您可以在 global.asax 中使用 PreRequestHandlerExecute 事件处理程序来处理这个

    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            //Check if user is authenticated
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                if (!authTicket.Expired)
                {
                    if (Session["XYZ"] == null)
                    {
                        //Session is null, redirect to login page
                        FormsAuthentication.SignOut();
                        Response.Redirect(FormsAuthentication.LoginUrl, true);
                        return;
                    }
                }
            }
        }
    

    或者,您可以编写一个 Httpmodule 并实现 context_AuthenticateRequest 来检查会话是否存在并相应地处理请求。

    希望对您有所帮助。

    由 Valamas 编辑

    有关会话错误的帮助,请参阅答案 https://stackoverflow.com/a/1446575/511438

    【讨论】:

    • 我想这就是我想要的。谢谢!如果它真的解决了我的问题,我会告诉你的。
    • 不,没有骰子。 “会话状态在此上下文中不可用。”
    • 稍后我会尝试一个Httpmodule并告诉你
    • Session 并不总是为图像文件、CSS、js 等内容页面加载。您可能希望在 HTTPModule 中实现 IRequiresSessionState。 stackoverflow.com/questions/1375627/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2020-03-09
    • 2015-09-23
    • 2015-03-25
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多