Sunday, April 16, 2023

How to prevent authentication cookie to be renewed on background (polling) AJAX call in ASP.net core

I know that we should be using Web Sockets / SignalR for server side push notifications instead of polling. But I was looking for a quick solution to a simple problem where there is an AJAX call being made after every 5 seconds to server.

This web application is using cookie based authentication with SlidingExpiration. So, whenever any AJAX call is being made to the server, the cookie is renewed. Which is causing the user to be logged in for an indefinite time.

I wanted to have one specific API call to be marked in a way so that it should not renew the cookie. In this way, non-active user will be logged out automatically, even with continuous AJAX calls being made in the background.

We can use OnCheckSlidingExpiration event in cookie settings where we can check if our specific action is being called then we can simply set ShouldRenew to false.

    cookieOptions.Events.OnCheckSlidingExpiration = context =>
    {
        var controllerName = context.Request.RouteValues["controller"] as string;
        var actionName = context.Request.RouteValues["action"] as string;
        if (controllerName == "MyController" && actionName == "MyAction")
            context.ShouldRenew = false;
        return Task.CompletedTask;
    };

I didn't like this solution but unfortunately, I couldn't find any ActionFilterAttribute or any other way so that I can set some type of flag in the pipeline from action level, which can tell cookie event to not renew the cookie. It seems like the cookie events are the first thing in the pipeline that's executed, and action filters are executed later.