Конечная точка KeepSessionAlive: я вызываю эту конечную точку каждые 5 минут, чтобы сеанс оставался активным и обновлялся токен защиты от подделки.
Код: Выделить всё
[HttpGet]
public IActionResult KeepSessionAlive()
{
var keepAliveValue = HttpContext.Session.GetString("KeepAlive");
_logger.LogInformation($"Previous KeepAlive: {keepAliveValue}");
HttpContext.Session.SetString("KeepAlive", DateTime.UtcNow.ToString());
_logger.LogInformation($"Updated KeepAlive: {DateTime.UtcNow}");
// Generate a new anti-forgery token
var tokens = HttpContext.RequestServices
.GetRequiredService()
.GetAndStoreTokens(HttpContext);
return Json(new
{
success = true,
antiForgeryToken = tokens.RequestToken
});
}
Код: Выделить всё
document.addEventListener("DOMContentLoaded", function () {
console.log('Document is loaded');
function keepSessionAlive() {
fetch('/Home/KeepSessionAlive', {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
})
.then(data => {
console.log('Session refreshed');
if (data.antiForgeryToken) {
// Update the anti-forgery token in the form or headers
document.querySelector('input[name="__RequestVerificationToken"]').value = data.antiForgeryToken;
}
})
.catch(error => {
console.log('Failed to keep session alive:', error);
})
.finally(() => {
// Schedule the next execution after 5 minutes
setTimeout(keepSessionAlive, 5 * 60 * 1000);
});
}
// Start the session-keeping mechanism
keepSessionAlive();
});
Код: Выделить всё
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SaveProjectDetails(ProjectDetails projectDetails)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid model state");
}
_logger.LogInformation("Anti-Forgery Token Validated Successfully");
// Save logic here
return Ok(new { success = true });
}
Код: Выделить всё
builder.Services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(720); // Cookie expiration time
options.SlidingExpiration = true; // Reset expiration on user activity
});
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(720); // Set session timeout
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Use HTTPS
options.Cookie.IsEssential = true;
options.Cookie.MaxAge = TimeSpan.FromMinutes(720); // Persist the cookie
});
builder.Services.AddAntiforgery(options =>
{
options.Cookie.Name = ".AspNetCore.Antiforgery";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.MaxAge = TimeSpan.FromMinutes(720); // Persist the cookie
});
Обновление: хотя это и не решение, удаление [ValidateAntiForgeryToken ] из действия решило проблему. Итак, это, очевидно, связано с токеном защиты от подделки (cookie).
Подробнее здесь: https://stackoverflow.com/questions/793 ... psessional