MVC session expiring but not authentication

萝らか妹 提交于 2019-12-03 06:30:57

I found my answer. Override the Authorize attribute. This seems like the most elegant approach:

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

        return base.AuthorizeCore(httpContext);
    }

}
vindh123

You could handle this in global.asax with PreRequestHandlerExecute event handler

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

Or, you could write a Httpmodule and implement context_AuthenticateRequest to check if session exists and handle the request accordingly.

Hope that helps.

Edit by Valamas

See answer https://stackoverflow.com/a/1446575/511438 for help with the session error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!