0

I am trying to implement session timeout in .net core application. Redirecting to login page is working fine in non-ajax request/full postback but not in case of ajax request. The login page is displayed within the layout/current page in ajax request.

I have written a middleware which will call the controller method first in which redirection login is written.Below is my code.

Middleware

 app.Use(async (ctx, next) =>
            {
                if (ctx.GetTenantContext<AppTenant>() == null && !ctx.Request.Path.ToString().Contains("/Home/Redirect"))
                {
                    string redirect = "/Home/Redirect/";

                    if (ctx.Request.Path.ToString().Contains("Admin"))
                    {
                        redirect = "/Home/Redirect/Admin";
                    }
                    else
                    {
                        redirect = "/Home/Redirect/Trainee";
                    }


                    ctx.Response.Redirect(redirect, true);
                }
                else
                {
                    await next();
                }
            });

Home Controller

[Route("/Home/Redirect/{AppType?}")]
        public async Task<IActionResult> Redirect()
        {
            string appType = string.Empty;
            string clientName = string.Empty;

            if (!string.IsNullOrEmpty(Convert.ToString(RouteData.Values["AppType"])))
            {
                appType = Convert.ToString(RouteData.Values["AppType"]);
            }

            await _signInManager.SignOutAsync();

            HttpContext.Session.Clear();

            if (!string.IsNullOrEmpty(appType))
            {
                if (appType == "Admin")
                {
                    if (HttpContext.Request.Cookies != null)
                    {
                        if (HttpContext.Request.Cookies["clientnamebe"] != null)
                        {
                            clientName = HttpContext.Request.Cookies["clientnamebe"].ToString();
                        }
                    }
                    return RedirectToRoute(new
                    {
                        controller = "Admin",
                        action = "Login",
                        clientname = clientName

                    });
                }
                else
                {
                    if (HttpContext.Request.Cookies != null)
                    {
                        if (HttpContext.Request.Cookies["clientnamefe"] != null)
                        {
                            clientName = HttpContext.Request.Cookies["clientnamefe"].ToString();
                        }
                    }
                    return RedirectToRoute(new
                    {
                        controller = "Account",
                        action = "Login",
                        clientname = clientName

                    });
                }
            }

            return View();
        }

and in Login method I am just returning a view

[Route("Account/Login/{clientname}", Name = ApplicationType.FRONTEND)]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true, Duration = 0)]
public async Task<IActionResult> TraineeLogin(string returnUrl)
{
  Return View();
}

My ajax request, though I am just loading related action results in div on tab click.

 $('#tabstrip a').click(function (e) {
            e.preventDefault();

            var tabID = $(this).attr("href").substr(1);
            localStorage.setItem("ClientCourseTab", '#'+tabID);
            $("#" + tabID).html("");
            var link = '@Url.Action("-1", "Course")';
            link = link.replace("-1", tabID);
            $("#" + tabID).load(link); // here actual request made
            var appendValue = tabID.replace('_FrontEnd', '');
            var appendValue = appendValue.replace('_', '');
            window.location.hash = appendValue;
            $(this).tab('show');
        });

Any help on this appreciated !

XamDev
  • 3,377
  • 12
  • 58
  • 97
  • Are you saying that you want the user to be redirected to login page even if an ajax request is made after the session has timed out? – sachin May 08 '17 at 13:37
  • yes exactly, user should be redirected to login page in ajax request if session times out – XamDev May 08 '17 at 13:40

1 Answers1

1

The server does return the Redirect response in this case for the ajax request but the user doesn't get redirected to the Login page. Why? The reason is that the HTTP redirect is implicitly processed by the browser and actually never arrives to the ajax success callback. The browser processes the redirect and delivers a 200 code with the content of the redirect's destination (the login page in your case).

This is not as simple as it sounds, there are few workarounds but all of those quite complicate things. Here is one solution that you might try to implement:

How to manage a redirect request after a jQuery Ajax call

Another solution can be to have some javascript code running at a specific interval on each page to check whether the session has expired (by querying the server which complicates things even more). Whenever this javascript code detects that the session has expired, user should be immediately taken to the login page instead of waiting for an ajax request to be triggered. The problem with querying the server would be that if you have some kind of sliding expiration of auth ticket on the server, the ticket might get renewed and session might never expire.

Community
  • 1
  • 1
sachin
  • 2,341
  • 12
  • 24