Last active
March 31, 2025 19:15
-
-
Save EmilySamantha80/c8f8e9cf5e14c2fd7e6a2837d012be38 to your computer and use it in GitHub Desktop.
Blazor Session Timeout Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <body> | |
| <Routes @rendermode="InteractiveServer" /> | |
| <script src="_framework/blazor.web.js"></script> | |
| @* Add the session helper JavaScript, used by SessionHelper.razor *@ | |
| <script src="js/session-helper.js"></script> | |
| </body> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Just add this line as the first piece of markup in the Layout file to insert it into every page that uses the layout. | |
| <SessionHelper /> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| window.SessionHelper = { | |
| TimeoutHandler: function (dotnethelper) { | |
| document.onmousedown = resetTimeDelay | |
| document.onkeypress = resetTimeDelay | |
| function resetTimeDelay() { | |
| dotnethelper.invokeMethodAsync("TimerInterval") | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @using Microsoft.AspNetCore.Authorization | |
| @using Microsoft.AspNetCore.Components.Authorization | |
| @using System.Security.Claims | |
| @using Microsoft.Graph | |
| @using Microsoft.Graph.Models | |
| @using BlazorApp1.Components.Layout | |
| @inject NavigationManager NavigationManager | |
| @inject IConfiguration Configuration | |
| @inject IJSRuntime JSRuntime | |
| @inject AuthenticationStateProvider AuthState | |
| @implements IDisposable | |
| @code { | |
| private System.Timers.Timer timerObj = new System.Timers.Timer(); | |
| private Timer? SessionTimer; | |
| private int SessionTimeoutSeconds; | |
| public void Dispose() | |
| { | |
| SessionTimer?.Change(Timeout.Infinite, 0); | |
| SessionTimer?.Dispose(); | |
| } | |
| protected override async Task OnAfterRenderAsync(bool firstRender) | |
| { | |
| await base.OnAfterRenderAsync(firstRender); | |
| if (firstRender) | |
| { | |
| // Identify whether the user is active or inactive using onmousemove and onkeypress in JS function. | |
| await JSRuntime.InvokeVoidAsync("SessionHelper.TimeoutHandler", DotNetObjectReference.Create(this)); | |
| } | |
| } | |
| protected override async Task OnInitializedAsync() | |
| { | |
| await base.OnInitializedAsync(); | |
| var appSettingsSection = Configuration.GetSection("AppSettings"); | |
| SessionTimeoutSeconds = appSettingsSection?.GetValue<int>("SessionTimeout") ?? 0; | |
| // Check if the timeout value has been set. | |
| // If not, this will result in the user never being logged out due to inactivity. | |
| if (SessionTimeoutSeconds != 0) | |
| { | |
| //Start the timer for idle state | |
| SessionTimer = new Timer(HandleSessionTimeout, null, TimeSpan.FromSeconds(SessionTimeoutSeconds), Timeout.InfiniteTimeSpan); | |
| } | |
| } | |
| // This method is called from the JavaScript function timeOutCall in session-helper.js | |
| // It gets called whenever activity is detected on the page. | |
| [JSInvokable] | |
| public void TimerInterval() | |
| { | |
| // If for some reason the timer is null, return. This should never happen. | |
| // If it does, the session will never be refreshed. | |
| if (SessionTimer == null) | |
| { | |
| return; | |
| } | |
| // Reset the timer when the user is active. | |
| SessionTimer.Change(TimeSpan.FromSeconds(SessionTimeoutSeconds), Timeout.InfiniteTimeSpan); | |
| } | |
| // This method is called when the session timeout is reached. | |
| private void HandleSessionTimeout(object? state) | |
| { | |
| InvokeAsync(async () => | |
| { | |
| // Log out when the user is inactive. | |
| var authState = await AuthState.GetAuthenticationStateAsync(); | |
| var user = authState?.User; | |
| if (user?.Identity?.IsAuthenticated ?? false == true) | |
| { | |
| if (user?.Identity?.Name == null) | |
| { | |
| return; | |
| } | |
| ForceSignout(user.Identity.Name); | |
| } | |
| }); | |
| } | |
| private void ForceSignout(string username) | |
| { | |
| // Code to sign out the user goes here | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment