如果用户的 cookie 已过期,我正在尝试使我的页面自动导航到登录页面。 我在页面上使用 javascript 来定期检查,并使用中间件来检查用户是否经过身份验证。 这似乎不起作用。 我假设这是因为它仍在滑动 cookie 的过期时间。 我如何检查 cookie,看看这是否是问题所在,而不是在这次通话中滑动它?
builder.Services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.SlidingExpiration = true;
});
app.UseMiddleware<SessionExpiryCheckMiddleware>();
public class SessionExpiryCheckMiddleware
{
private readonly RequestDelegate _next;
public SessionExpiryCheckMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Only check session for specific paths
if (context.Request.Path.StartsWithSegments("/SessionStatus"))
{
var isAuthenticated = context.User.Identity.IsAuthenticated;
// If user is authenticated, proceed without extending session
if (!isAuthenticated)
{
// Invalidate session
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
}
await _next(context);
}
}
setInterval(function () {
fetch('/SessionStatus', {
method: 'GET',
credentials: 'same-origin'
})
.then(response => {
console.log(response.status);
if (response.status === 401) {
// Session has expired, redirect to login page
window.location.href = '/Identity/Account/Login';
}
})
.catch(error => {
console.error('Error checking session status:', error);
});
}, 5000);
为此,您需要创建注销端点:
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return Ok();
}
然后从前端 JavaScript 代码调用它。