Prevent session timeout from resetting for periodical ajax calls

544 Views Asked by At

In my ASP.NET MVC application there is a periodical ajax call to fetch new notifications for the current user. However this call resets the idle timeout for the current session, causing the session to never expire. This is a security risk. How can I prevent certain endpoint calls from resetting the idle timeout?

1

There are 1 best solutions below

1
Alexey Rumyantsev On

Session state in ASP NET Core is maintained by SessionMiddleware, it is design is pretty simple. I will omit starting part where session is loaded, you are interested in this part where next middleware calls are wrapped in such way.

try
{
    await _next(context); //Here are all other middlewares executed
}
finally
{
    context.Features.Set<ISessionFeature>(null);

    if (feature.Session != null)
    {
        try
        {
            await feature.Session.CommitAsync(); //Here your session is commited and prolongated
        }
        catch (OperationCanceledException)
        {
            _logger.SessionCommitCanceled();
        }
        catch (Exception ex)
        {
            _logger.ErrorClosingTheSession(ex);
        }
    }
}

So if you are accessing session read-only you can just not commit it when you are hitting your periodical endpoint, you can figure it out from HttpContext context. If you prevent block of code that commits session from execution it will not put new entry in IDistributedCache renewing it's sliding expiration and session will remain unaltered.

You also have to write analogue of SessionMiddlewareExtensions class where UseSession extension method is defined and provide your own implementation registering your custom middleware.