Hi @Balu Raju ,
You can use JavaScript onmousemove
and onkeypress
events to trigger the Timer function in a Razor component can identify whether a user is active or inactive.
Refer to the follow sample and steps:
- Create a new Asp.net 6 Blazor Server application and select the Individual Accounts Authentication Type.
- In the _Layout.cshtml page, add the following scripts at the bottom of the body. 245299-javascript.txt
- In the MainLayout.razor component, setting the timer.
@using System.Timers @inherits LayoutComponentBase @inject NavigationManager UriHelper @inject IJSRuntime JSRuntime <PageTitle>BlazorServerAutoLogout</PageTitle> <div class="page"> <div class="sidebar"> <NavMenu /> </div> <main> <div class="top-row px-4 auth"> <LoginDisplay /> <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a> </div> <article class="content px-4"> @Body </article> </main> </div> @code { [CascadingParameter] private Task<AuthenticationState> stateAuthenticate { get; set; } private Timer timerObj; protected override async Task OnInitializedAsync() { } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { // Set the Timer delay. 5000 milliseconds, you can change it to 10 mins. timerObj = new Timer(5000); timerObj.Elapsed += UpdateTimer; timerObj.AutoReset = false; // Identify whether the user is active or inactive using onmousemove and onkeypress in JS function. await JSRuntime.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this)); //StateHasChanged(); } } [JSInvokable] public void TimerInterval() { // Resetting the Timer if the user in active state. timerObj.Stop(); // Call the TimeInterval to logout when the user is inactive. timerObj.Start(); } private void UpdateTimer(Object source, ElapsedEventArgs e) { InvokeAsync(async() => { // Log out when the user is inactive. var authstate = await stateAuthenticate; if (authstate.User.Identity.IsAuthenticated) { UriHelper.NavigateTo("/Identity/Account/LogOut", true); } }); } }
- In the LogOut.cshtml page(you can find it from the Identity Areas), since we are using the NavigateTo method, we have to add the OnGet method to logout.
The output as below: after 5 seconds, it will auto logout. You can change the timer the the MainLayout.razor component
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion