Session expiring and auth cookie remaining

2019-07-30 18:58发布

I'm having an issue where my session is expiring,

Session["UserId"] = userId;

but the authentication cookie is still there so the [authorize] attribute is still allowing the user to navigate the system until the system tries to read the session variables and errors out. Null exception

Are there any thoughts on how to make the auth cookie go away when the session expires? I would certainly appreciate any insight as I am new to ASP.NET MVC 3.

2条回答
Fickle 薄情
2楼-- · 2019-07-30 19:08

This is bad practice, see this link for a deeper explanation. Basically, by logging in as anyone, and then get hold of someone else session key you can steal that identity.

I would recommend you to embedd the id of the user in the auth cookie instead, see this question on the subject. Then you could merely use the session as a cache if you like, just compare the sessions id with the one stored in the auth cookie. Do that in, for example, global.asax so you don't have to alter your application

查看更多
老娘就宠你
3楼-- · 2019-07-30 19:30

There are many ways you can do this. Here is just one idea.

public class ControllerBase : Controller
{
    public ControllerBase()
        : base()
    {
        this.VerifySession();  
    }

    /// <summary>
    /// Indicates whether the session must be active and contain a valid customer.
    /// </summary>
    protected virtual bool RequiresActiveSession
    {
        get { return true; }
    }

    public void VerifySession()
    {
        if (this.RequiresActiveSession && Session["UserId"] == null)
        {
            Response.Redirect(Url.Action("LoginPage"));
        }
    }

}

public class HomeController : ControllerBase
{
    protected override bool RequiresActiveSession
    {
        get
        {
            return true;
        }
    }

    public ActionResult Index()
    {
        return View();
    }
}

Basically you have a controller base which will handle validating the session. And any controller that inherits from it can specify if it wants to validate the session or not.

OR

you could create a custom Action Filter which allows you to attribute your controller or actions and hook your code into the processing pipeline of before executing your controllers actions.

查看更多
登录 后发表回答