【发布时间】:2014-06-20 23:21:11
【问题描述】:
我在 MVC5 中使用 cookie 身份验证。我的网页严重依赖每 1-5 秒经过身份验证和未经身份验证的 Ajax 调用来保持数据更新。因此,我的用户永远不会退出该站点。
我的理想场景:如果用户正在我的网站上积极浏览或执行操作,请保持会话处于活动状态。如果他们在 10 分钟后打开页面,我希望他们的会话超时,我将使用失败的 Ajax 调用重定向到登录页面。我认为这最好在控制器或操作级别完成。
我尝试按照以下建议控制会话状态行为,但会话仍然没有超时。在每秒点击一次 ReadOnly/Public 65 秒后,我调用 ReadOnly/Authorized 并成功从中检索数据。
这是我的 CookieAuthentication 配置。
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(1),
});
}
我的测试页面:
<div id="public"></div>
<div id="authorized"></div>
@section scripts{
<script>
function poll(times) {
var url = '/ReadOnly/Public';
$.ajax({
url: url,
dataType: 'json',
data: null,
cache: false,
success: function (data) {
$('#public').html(times + ' ' + data.test);
},
error: function (data) {
$('#public').html(times + ' ' + 'failed');
}
});
};
function checkAuth(times) {
var url = '/ReadOnly/Authorized';
$.ajax({
url: url,
dataType: 'json',
data: null,
cache: false,
success: function (data) {
$('#authorized').html(times + ' ' + data.test);
},
error: function (data) {
$('#authorized').html(times + ' ' + 'failed');
}
});
};
$(function () {
var times = 1;
setInterval(function () {
poll(times);
times++;
}, 1000);
setInterval(function () {
checkAuth(times);
}, 65000);
});
</script>
}
并测试控制器代码(尝试使用禁用和只读选项)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
namespace SessionTest.Controllers
{
[SessionState(SessionStateBehavior.ReadOnly)]
public class ReadOnlyController : Controller
{
[Authorize]
public ActionResult Authorized()
{
return Json(new
{
test = "ReadOnly and Authorized"
}, JsonRequestBehavior.AllowGet);
}
public ActionResult Public()
{
return Json(new
{
test = "ReadOnly and Public"
}, JsonRequestBehavior.AllowGet);
}
}
}
【问题讨论】:
-
当前实现的表现如何?无论用户做什么,它都会在 10 分钟内退出,还是在用户空闲 10 分钟后退出?
-
用户从不注销。他们的会话无限期打开,因为 Ajax 调用每 5 秒进行一次,超时窗口为 10 分钟。
-
你为什么要这样做?如果他们离开网页,或手动注销(我假设该选项仍然存在)会话将终止。如果没有,那一切听起来都很好。我讨厌超时,他们很痛苦。
-
从用户体验的角度,想想一个金融应用。您想强制执行超时,这样用户就不会离开他们的办公桌,然后他们的钱就会被抽走。从服务器资源的角度来看,如果用户不活跃,我想保留网络和数据库负载。
-
我遵守规则,帮助那些愿意帮助自己的人。您对授权控制器有一个无限循环,不愿意实现会话状态,并且显然不愿意编写自己的 cookie 提供程序。你祈求奇迹,不愿意与任何人一起满足你的需要。我删除我的答案,祝你好运。
标签: ajax asp.net-mvc-5