0

How can I manage Session across multiple tabs in ASP.NET mvc. As in let's say I have opened same page in two tabs and I log out from one, then I should automatically be redirected to login page from the other.

jay parekh
  • 9
  • 1
  • 5
  • Have a look at [this post](https://syfuhs.net/2013/03/24/real-time-user-notification-and-session-management-with-signalr-part-2/) for one approach to this using SignalR. – NightOwl888 May 19 '16 at 11:05

2 Answers2

0

Use Session and call as overrided method in base controller to redirect to login page when it expires. Use using System.Security.Principal;for CustomPrincipal class file below.

An example of using session in a class say SessionPersistor:

public static long UserId
    {
        get
        {


            if (HttpContext.Current == null) return 0;
            if (HttpContext.Current.Session[userId] != null)
                return Convert.ToInt64(GetObjectFromSession(userId));
            return 0;
        }
        set
        {

            SetItemInSession(value, userId);

        }
    }

public static object GetObjectFromSession(string key)
    {
        return HttpContext.Current.Session[key];
    }

In Base Controller:

protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!string.IsNullOrEmpty(SessionPersister.UserName)) { filterContext.HttpContext.User = new CustomPrincipal(new CustomIdentity(SessionPersister.UserFullName)); }
        else { InvalidRequest(filterContext, "101", "Access denied.", "Session expired or You dont have access to this page."); }

        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.AppendHeader("prod-tool", "no-cache");
        base.OnAuthorization(filterContext);
    }

Create a CustomPrincipal class: (In case of using this example)

public class CustomPrincipal : IPrincipal
{    
public CustomPrincipal(CustomIdentity identity)
    {
        this.Identity = identity;
    }
}
public class CustomIdentity : IIdentity
{
    public CustomIdentity(string name)
    {
        this.Name = name;
    }
}
Bharath theorare
  • 524
  • 7
  • 27
0

Use a Filter for authorzation handling - a global filter.
In the config you can configure the login URL, so that the user should be redirected to your page when he/she is not authorized.
If your application opened the second browser window (tab) you can write a java script function which iterates over all child windows and calls a refresh.

How to find child windows: How to get the references of all already opened child windows

Community
  • 1
  • 1
Durgil
  • 31
  • 3