ASP.NET Core 8.0 - Admin Idle Logout

This article will describe the implementation of an idle logout function which combines JavaScript and html in a razor partial view. You should review the earlier articles of the Cookies And Claims Project series. Registered users can download the ASP.NET Core 8.0 - Cookies And Claims Project for free.

Cookies And Claims Project and Article Series

Free project download for registered users!

I developed the Cookies And Claims Project (CACP) to demonstrate a simple cookie authentication scheme and claim-based authorization with a clear and modifiable design. The CACP is developed with Visual Studio 2022 and the MS Long Term Support (LTS) version .NET 8.0 framework. All Errors, Warnings, and Messages from Code Analysis have been mitigated. The CACP implements utilities like an AES Cipher, Password Hasher, native JavaScript client form validation, password requirements UI, Bootstrap Native message modal generator, loading/spinner generator, SignalR online user count, and an automatic idle logout for users with administration permissions.

The CACP implements an Admin Idle Logout feature which automatically logs out administrator users if they have not interacted with the browser's web page for a set amount of time. The CACP implements a static class named AppSettings.cs for global project settings which declares the Admin Idle Logout settings.

AppSettings.cs:
/// <summary>
/// Set to automatically logout Admin users who are idle longer than the <see cref="AdminIdleLogoutThreshold" />
/// plus the <see cref="AdminIdleLogoutCountdown" />.
/// </summary>
/// <remarks>
/// A click, mousemove, or keypress event resets the idle timer. These event listeners are only enabled
/// when the user is authenticated.
/// </remarks>
public static readonly bool AdminIdleLogoutEnabled = true;
/// <summary>
/// Used to set the number of minutes the user must be idle before the logout warning banner is displayed.
/// </summary>
public static readonly int AdminIdleLogoutThreshold = 10;
/// <summary>
/// Used to set the number of seconds the logout warning banner is displayed.
/// </summary>
public static readonly int AdminIdleLogoutCountdown = 15;

The CACP implements a _AdminIdleLogoutPartial.cshtml partial view in the Pages' Shared folder. This partial view implements the event listeners, timers, and css to display a countdown warning before calling an AJAX logout method. If the AdminIdleLogout is enabled, the user is authenticated, and the user has the AdministratorClaimType, the _AdminIdleLogoutPartial is loaded from the _Layout.

Pages > Shared > _Layout.cshtml:
<div class="container">
    <main role="main" class="pb-3">
        @RenderBody()
    </main>
    <partial name="_CookieConsentPartial" />
    @if ((User.Identity?.IsAuthenticated ?? false) && AppSettings.AdminIdleLogoutEnabled && User.HasClaim(c => c.Type == AppSettings.AdministratorClaimType))
    {
        <partial name="_AdminIdleLogoutPartial" />
    }
</div>

If a click, mousemove, or keypress event every AdminIdleLogoutThreshold minutes does not reset the timer, a warning is displayed for AdminIdleLogoutCountdown seconds. A click, mousemove, or keypress event resets the idle timer.

Admin idle logout warning..

The AJAX logout method is invoked when the Inactivity Timeout expires.

Pages > Shared > _AdminIdleLogoutPartial.cshtml:
function ajaxLogout() {
    return fetch('/account/logout?handler=ajaxlogout',
        {
            method: 'post', credentials: 'same-origin', headers: { 'Content-Type': 'application/json;charset=UTF-8',
                'RequestVerificationToken': document.querySelector('input[type="hidden"][name="__RequestVerificationToken"]').value
            }
        })
        .then(function (response) { if (response.ok) return response.text(); else throw Error('Response Not OK'); })
        .then(function (text) { try { return JSON.parse(text); } catch (err) { throw Error('Method Not Found'); } })
        .then(function (responseJSON) { if (responseJSON) location.assign('/members/idlelogout'); })
        .catch(function (error) { showMessageModal(error, 'alert-danger'); });
}

The AJAX logout method posts to the AjaxLogout event implemented on the Logout page.

Pages > Account > Logout.cshtml.cs:
public async Task<JsonResult> OnPostAjaxLogoutAsync()
{
    await HttpContext.SignOutAsync(AppSettings.ApplicationScheme);
    return new JsonResult(true);
}

If the AJAX logout method completes successfully, the user is redirected to a logged out notice page.

Pages > Members > IdleLogoutl:
Admin idle logged out..
Ken Haggerty
Created 07/24/24
Updated 08/29/24 16:14 GMT

Log In or Reset Quota to read more.

Successfully completed. Thank you for contributing.
Contribute to enjoy content without advertisments.
Something went wrong. Please try again.

Comments(0)

Loading...
Loading...

Not accepting new comments.

Submit your comment. Comments are moderated.

User Image.
DisplayedName - Member Since ?