mnu*_*sir 1 asp.net-core blazor
我正在 .NET 6 中的Blazor Server 版本中创建一个 Web 应用程序。为了进行身份验证,我使用ASP.NET Core Identity。现在我的应用程序中需要一个功能。如果应用程序空闲一段特定时间(例如 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;
});
Run Code Online (Sandbox Code Playgroud)
如果我点击任何链接,我还应该做什么才能注销?另一件事是这条线
options.ExpireTimeSpan = TimeSpan.FromMinutes(5)
Run Code Online (Sandbox Code Playgroud)
真的会计算空闲时间吗?请告诉我。
我更喜欢在这些情况下使用 JavaScript,您可以使用Timer计算空闲状态秒数,如果计时器结束,那么您应该触发一个处理程序,将用户注销,甚至不需要单击任何链接或执行任何操作。
如果您同意,请按照以下步骤操作:
wwwroot/js1- 在目录中创建一个具有适当名称(例如: )的JavaScript 文件,auth-helper.js其中包含以下内容:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
~/Pages/_Layout.cshtml2-在 .NET 6 或~/Pages/_Host.cshtml.NET 5中添加脚本标记:
<script src="./js/auth-helper.js"></script>
Run Code Online (Sandbox Code Playgroud)
initializeInactivityTimer3-在 中添加注销实现和 JS 函数的调用MainLayout,并确保将其添加到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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3075 次 |
| 最近记录: |