【问题标题】:Logout after a specific idle time in ASP.NET Core Identity在 ASP.NET Core 标识中的特定空闲时间后注销
【发布时间】:2022-08-15 02:00:57
【问题描述】:

我正在创建一个 Web 应用程序布雷泽.NET 6 中的服务器版本。对于身份验证,我正在使用ASP.NET Core 标识.现在我需要在我的应用程序中添加一个功能。如果应用程序在特定时间(如 10 分钟)处于空闲状态,它将注销。我在Program.cs 文件中添加了以下代码。但问题是在特定时间跨度之后,如果我刷新应用程序然后它会注销。但是,如果我单击应用程序的任何链接,则什么也不会发生。

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.Cookie.Name = \"Horus\";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = \"/Identity/Account/Login\";
    options.LogoutPath = \"/Identity/account/logout\";
    options.AccessDeniedPath = \"/Identity/Account/Login\";
    options.SlidingExpiration = true;
});

如果我单击任何链接,我还应该做些什么来注销?另一件事是这条线

options.ExpireTimeSpan = TimeSpan.FromMinutes(5)

真的算空闲时间吗?请告诉我。

  • 您点击的链接 - 确保这些链接不是公开的。这意味着他们应该只要求通过身份进行身份验证,然后您将在单击它们时被重定向。

标签: asp.net-core blazor


【解决方案1】:

我更喜欢在这些情况下使用 JavaScript,您可以使用Timer 来计算空闲状态秒数,如果计时器结束,那么您应该触发一个处理程序,该处理程序将用户注销,甚至无需单击任何链接或执行任何操作。

如果您觉得这没问题,请按照以下步骤操作:

1- 在wwwroot/js 目录中创建一个具有适当名称(例如:auth-helper.js)的 JavaScript 文件,内容如下:

function initializeInactivityTimer(dotnetHelper) {
    var timer; 
    //the timer will be reset whenever the user clicks the mouse or presses the keyboard
    document.onmousemove = resetTimer;
    document.onkeypress = resetTimer;

    function resetTimer() {
        clearTimeout(timer);
        timer = setTimeout(logout, 600000); //600,000 milliseconds = 10 minuts
    }

    function logout() {
        dotnetHelper.invokeMethodAsync("Logout");
    }

}

2- 在index.html 中添加脚本标签:

<script src="./js/auth-helper.js"></script>

3- 在MainLayout 中添加注销实现和initializeInactivityTimer JS 函数的调用,并确保将其添加到MainLayout 而不是页面或组件,以便确保DotNetObjectReference 在任何时候都处于活动状态称为:


protected override async Task OnInitializedAsync()
{
    //Start the timer for idle state
    await js.InvokeVoidAsync("initializeInactivityTimer", DotNetObjectReference.Create(this));
}


[JSInvokable]
public async Task Logout()
{
    var authState = await AuthenticationState;
    if (authState.User.Identity.IsAuthenticated)
    {
        //implement the logging out process here
        //this might be navigation to the Logout page 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2019-03-17
    • 1970-01-01
    • 2013-01-12
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多