Live Chat Icon For mobile
Live Chat Icon

How do you initiate automatic logout when a user is inactive in Blazor?

Using JavaScript onmousemove and onkeypress events to trigger the Timer function in a Razor component can identify whether a user is active or inactive. If the user has not performed any onmousemove or onkeypress events, the user is considered in an inactive state and the Timer function is called after certain TimeInterval to log the user out.

Follow these steps to log the user out automatically if they’re not active:

  1. Call the onmousemove and onkeypress properties in a JavaScript function to fire the Timer function in the Razor component.
    [_Host.cshtml]

    <body>
        // . . .
        <script>
            function timeOutCall(dotnethelper) {
                document.onmousemove = resetTimeDelay;
                document.onkeypress = resetTimeDelay;
     
                function resetTimeDelay() {
                    dotnethelper.invokeMethodAsync("TimerInterval");
                }
            }
        </script>
    </body>

  2. Now call the Timer method to identify whether the user is active or not. Add navigation to the logout action when the user is inactive.
    [MainLayout.razor]

    @using System.Timers
    @inject NavigationManager UriHelper
    @inject IJSRuntime JSRuntime
     
    // . . .
    @code {
        [CascadingParameter]
        private Task<AuthenticationState> stateAuthenticate { get; set; }
        private Timer timerObj;
     
        protected override async Task OnInitializedAsync()
        {
            // Set the Timer delay.
            timerObj = new Timer(7000);
            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));
        }
     
        [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("logout", true);
                }
            });
        }
    }

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.