Multi-Browser Session Logout in ASP.NET Core Without SignalR

Introduction

The Automatic Multi-Browser Logout feature is designed to address this need by providing a robust and convenient solution to safeguard your account. This innovative feature ensures that when you log out from one browser, you are automatically logged out from all other active sessions, regardless of the device or platform.

the Automatic Multi-Browser Logout feature enhances security and offers a seamless user experience. Whether you are using multiple devices for work. this feature ensures that your sessions are consistently terminated across all browsers, protecting your sensitive information from unauthorized access. With benefits such as enhanced security, convenience, and a consistent logout experience

To achieve the functionality in ASP.NET CORE MVC, you can follow these steps.

Step 1. Add a Model for store session ID with a particular user basis.

   public class Session
    {
        public int? UserId { get; set; }
        public string Sessionid { get; set; }
    }

Step 2. Define methods for Insert, Delete, and Get session ID and userID in IRepositary.cs

IRepositary.cs


public interface ICommonRepository : IDisposable, IRepository
  {
Task<CustomerResult> SessionInsert(Session customer);
Task<CustomerResult> DeleteSessionId(string sessionid, int userid);
Task<IEnumerable<Session>> GetSessionExist(string sessionid, int userid);
  }

Step 3. Implementation of all Interfaces as defined in Step-2 as we required session insert in each login and check session Exist and Delete session if Logoutby user in Browser.

Repository. cs

 public class CommonRepository : RepositoryBase, ICommonRepository
    {

      public Task<CustomerResult> SessionInsert(Session customer)
        {
            DynamicParameters param = new DynamicParameters();
            object[] objArray = new object[] {
                    //"int_CustomerId", customer.CustomerId!=null?customer.CustomerId:0,
                    "ACTION","A",
                    "UserId",customer.UserId,
                    "Session",customer.Sessionid
               };
            param = objArray.ToDynamicParameters("PAR_OUT");
            var result = Connection.Query<string>("USP_SESSIONSTORE", param, commandType: 
 System.Data.CommandType.StoredProcedure);
            string response = param.Get<string>("PAR_OUT");
            CustomerResult customerResult = new CustomerResult() { Remark = response };
            return Task.FromResult(customerResult);
        }

     public Task<CustomerResult> DeleteSessionId(string sessionid, int userid)
        {
            DynamicParameters param = new DynamicParameters();
            object[] objArray = new object[] {
                    //"int_CustomerId", customer.CustomerId!=null?customer.CustomerId:0,
                    "ACTION","B",
                    "Session",sessionid,
                    "UserId",userid
               };
            param = objArray.ToDynamicParameters("PAR_OUT");
            var result = Connection.Query<string>("USP_SESSIONSTORE", param, commandType: System.Data.CommandType.StoredProcedure);
            string response = param.Get<string>("PAR_OUT");
            CustomerResult customerResult = new CustomerResult() { Remark = response };
            return Task.FromResult(customerResult);
        }

      public async Task<IEnumerable<Session>> GetSessionExist(string session, int userid)
        {
            DynamicParameters _params = new DynamicParameters();
            _params.Add("ACTION", "C");
            _params.Add("Session", session);
            _params.Add("UserId", userid);

            var result = await Connection.QueryAsync<Session>("USP_SESSIONSTORE", _params, commandType: CommandType.StoredProcedure);
            return result;
        }
}

Step 4. Insert the Session ID and User Login ID into the Database while User Login and add the below code in the Login Method defined Inside Controller. cs

Controller. cs

 public ActionResult Login()
        {
     #region-----Insert Session into DataBase-------------------------------
                                Session obj = new Session();
                                obj.UserId = loggedInUser.UserId;
                                obj.Sessionid = HttpContext.Session.Id;
                                var SaveSession = _commonRepository.SessionInsert(obj).Result;

      #endregion------------------------------------------------------------
}

//Check The Session in Each 5 second
   public IActionResult CheckSession()
        {
            LoggedInUser profile = HttpContext.Session.Get<LoggedInUser>(KeyHelper.UserKey);
            if (profile != null)
            {
                var sessionExists = _commonRepository.GetSessionExist(HttpContext.Session.Id, profile.UserId).Result;
                if (sessionExists.Count() != 0)
                {
                    return Ok("valid");
                }
                else
                {
                    return Ok("expired");
                }
            }
            else
            {
                return RedirectToAction("Logout", "Account");
            }
        }

[HttpGet]
        public IActionResult Logout()
        {
            #region------for delete session based on user id------
            LoggedInUser profile = HttpContext.Session.Get<LoggedInUser>(KeyHelper.UserKey);
            if (profile != null)
            {
    var DeleteSession = _commonRepository.DeleteSessionId(HttpContext.Session.Id,profile.UserId);
            }
            #endregion---------------------------------------------------------------
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.Session.Clear();
            HttpContext.Session.Remove(HttpContext.Session.Id);
}

Step 4. Add the Javascript function to the Layout. cshtml page for checking sessions at each 5-second time interval.

Layout. cshtml

<script type="text/javascript">
        (function poll() {
            setTimeout(function () {
                $.ajax({
                    url: '/Account/CheckSession',
                    success: function (data) {
                        if (data === 'expired') {
                            // Session expired, perform logout action
                            window.location.href = "/Account/Logout";
                        } else {
                            // Session still valid, continue polling
                            poll();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error
                        console.error(error);
                    }
                });
            }, 5000); // Poll every 5 seconds
        })();

    </script>

Conclusion

By ensuring that logging out from one session automatically terminates all other active sessions, this feature significantly reduces the risk of unauthorized access and enhances your overall online security.

Implementing this feature not only defines our logout process but is also protected across all devices. Embrace the future of secure, hassle-free browsing with Automatic Multi-Browser Logout and experience a consistent, unified approach to managing your online sessions.


Similar Articles