Home Asp.net MVC - How to check session expire for Ajax request
Reply: 5

Asp.net MVC - How to check session expire for Ajax request

paul sim
1#
paul sim Published in 2017-09-14 04:55:55Z

We are using Ajax call across the application- trying to find out a global solution to redirect to login page if session is already expired while trying to execute any Ajax request. I have coded following solution taking help from this post - Handling session timeout in ajax calls

NOT SURE WHY IN MY CARE EVENT "HandleUnauthorizedRequest" DOES NOT GET FIRED.

Custom Attribute:

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CheckSessionExpireAttribute :AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var url = new UrlHelper(filterContext.RequestContext);
                var loginUrl = url.Content("/Default.aspx");

                filterContext.HttpContext.Session.RemoveAll();
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.HttpContext.Response.Redirect(loginUrl, false);
                filterContext.Result = new EmptyResult();
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }

        }

    }

Using Above custom attribute as follow in controller action:

 [NoCache]
 [CheckSessionExpire]
 public ActionResult GetSomething()
 {
  }

AJAX Call(JS part):

function GetSomething()
{
   $.ajax({
        cache: false,
        type: "GET",
        async: true,
        url: "/Customer/GetSomething",
        success: function (data) {

        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
}

Web Config Authentication settings:

  <authentication mode="Forms">
      <forms loginUrl="default.aspx" protection="All" timeout="3000" slidingExpiration="true" />
    </authentication>

I am try to check it by deleting browser cooking before making ajax call but event "CheckSessionExpireAttribute " does not get fired- any idea please.

Thanks,

@Paul

Hüseyin BurakKaradag
2#
Hüseyin BurakKaradag Reply to 2017-09-21 09:45:04Z

I checked and tested the code, looks like clearly.. the problem is that the ajax call is wrong..

I fix Ajax code, try this..

function GetSomething() {
        $.ajax({
            cache: false,
            type: "GET",
            async: true,
            url: "/Customer/GetSomething",
            success: function (data) {

            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });
    }
Greg
3#
Greg Reply to 2017-09-26 16:16:33Z

On HttpContext.Request.IsAjaxRequest()

Please see this related article on why an Ajax request might not be recognized as such.

XMLHttpRequest() not recognized as a IsAjaxRequest?

It looks like there is a dependency on a certain header value (X-Requested-With) being in the request in order for that function to return true.

You might want to capture and review your traffic and headers to the server to see if indeed the browser is properly sending this value.

But, are you even sure it's hitting that line of code? You might also want to debug with a break point and see what values are set.

On Session vs Authentication

Authorization and Session timeout are not always exactly the same. One could actually grant authorization for a period longer than the session, and if the session is missing, rebuild it, as long as they are already authorized. If you find there is something on the session that you'd be loosing that can't be rebuilt, then perhaps you should move it somewhere else, or additionally persist it somewhere else.

Form Authentication cookies default to timeout after 30 minutes. Session timeout default is 20 minutes.

Session timeout in ASP.NET

HandleUnauthorizedRequest not overriding

Luca Corradi
4#
Luca Corradi Reply to 2017-09-26 15:30:19Z

I think that is only a client-side problem. In web server you can just use the classic Authorize attribute over actions or controllers. That will validate that the request is authenticated (if there's a valid authentication cookie or authorization header) and sets HTTP 401 if not authenticated.

Note: a session will automatically be recreated if you don't send authorization info in the request, but the request will not be authorized

Solution

Then the javascript client you must handle the redirect (browsers do it automatically but with ajax you need to do it manually)

$.ajax({
    type: "GET",
    url: "/Customer/GetSomething",
    statusCode: {
       401: function() {
          // do redirect to your login page
          window.location.href = '/default.aspx'
       }
    }
});
chibao
5#
chibao Reply to 2017-09-27 10:37:44Z

Sorry to say that: The solution you need is impossible. The reason is:

  • To redirect user to login page, we have 2 methods: redirect at server, redirect at client
  • In your case, you're using Ajax so we have only 1 method: redirect at client (reason is, basically, Ajax means send/retrieve data to/from server. So it's impossible to redirect at server)
  • Next, to redirect at client. Ajax need to information from server which say that "redirect user to login page" while global check session method must be return Redirect("url here").
  • clearly, global check session method can not return 2 type (return Redirect(), return Json,Xml,Object,or string)

After all, I suggest that:

  • Solution 1: Don't use ajax
  • Solution 2: You can use ajax, but check session timeout method at server which is not globally. Mean that you must multiple implement (number of ajax call = number of implement)
Tiramonium
6#
Tiramonium Reply to 2017-09-27 17:23:58Z

If I got the question right (and even if I didn't, thanks anyway, helped me solve my own situation), what you wanted to avoid was having your login page to load inside an element which was supposed to display a different View via Ajax. That or get an exception/error status code during a Ajax form post.

So, in short, the annotation class will need to override 2 methods, not just HandleUnauthorizedRequest, and it will redirect to a JsonResult Action that will generate the parameters for your Ajax function to know what to do.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class SessionTimeoutAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;
        base.OnAuthorization(filterContext);
        if (!user.Identity.IsAuthenticated) {
            HandleUnauthorizedRequest(filterContext);
        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new { controller = "AccountController", action = "Timeout" }));
        }
    }
}

Then set this annotation in your authentication Action, so every time it gets called, it will know where the request came from, and what kind of return it should give.

[AllowAnonymous]
[SessionTimeout]
public ActionResult Login() { }

Then your redirected Json Action:

[AllowAnonymous]
public JsonResult Timeout()
{
    // For you to display an error message when the login page is loaded, in case you want it
    TempData["hasError"] = true;
    TempData["errorMessage"] = "Your session expired, please log-in again.";

    return Json(new
    {
        @timeout = true,
        url = Url.Content("~/AccountController/Login")
    }, JsonRequestBehavior.AllowGet);
}

Then in your client function (I took the privilege of writing it as $.get() instead of $.ajax():

$(document).ready(function () {
    $("[data-ajax-render-html]").each(function () {
        var partial = $(this).attr("data-ajax-render-html");
        var obj = $(this);

        $.get(partial, function (data) {
            if (data.timeout) {
                window.location.href = data.url;
            } else {
                obj.replaceWith(data);
            }
        }).fail(function () {
            obj.replaceWith("Error: It wasn't possible to load the element");
        });
    });
});

This function replaces the html tag with this data-ajax-render-html attribute, which contains the View address you want to load, but you can set it to be loaded inside the tag by changing replaceWith for the html() property.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.562039 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO