Search code examples
asp.netwebformsasp.net-identity-2

Allow only a single login session per user


Essentially I am asking this question here, but I am using ASP Identity instead of the ASP.Net Membership provider, and with that, that answer is of no use to me.


Solution

  • Figured out how to do it. On login I call this:

    var key = user.UserName;
    var timeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
    HttpContext.Current.Cache.Insert(key, Session.SessionID, null, DateTime.MaxValue, timeOut, CacheItemPriority.NotRemovable, null);
    

    And this in the Global.asax

    if (Session["username"] != null)
        {
            var cacheKey = Session["username"].ToString();
            if ((string) HttpContext.Current.Cache[cacheKey] != Session.SessionID) LogOut();
        }