How to detect user's inactiveness in Blazor server app

Balu Raju 81 Reputation points
2022-09-27T12:47:00.917+00:00

We are developing a Blazor Server App, with no single line of JS written so far. This may be a basic question.
My question is how to detect the user's inactiveness on Blazor server app and prompt them to either continue or logout
or simply log them out after say 10 minutes.

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,602 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,456 Reputation points Microsoft Vendor
    2022-09-28T02:50:02.497+00:00

    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:

    1. Create a new Asp.net 6 Blazor Server application and select the Individual Accounts Authentication Type.
    2. In the _Layout.cshtml page, add the following scripts at the bottom of the body. 245299-javascript.txt
      245334-image.png
    3. 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);  
                   }  
               });  
           }  
       }   
      
    4. 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. 245324-image.png

    The output as below: after 5 seconds, it will auto logout. You can change the timer the the MainLayout.razor component

    245269-1.gif


    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

    4 people found this answer helpful.
    0 comments No comments

  2. Balu Raju 81 Reputation points
    2023-11-01T18:01:37.1266667+00:00

    I agree with HeMan. when the marketing Hype for Blazor is to leverage what I know already better , which in my case it is C# I should be able to do this without my unfavorable JS. I also understand blazor does not work without JS, that is for the underlying plumbing work, which I do not need to worry about as I'm going to leverage what I know in C#. I just do not want to write JS Code or try not to as much as possible when I design my app with Blazor, whether it is web assembly or server or hybrid. So I expect to do things in C# what I want to do rather than in JS.

    1 person found this answer helpful.
    0 comments No comments

  3. Balu Raju 81 Reputation points
    2022-09-28T03:21:12.197+00:00

    Is there a way to without adding the Javascript code?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.