我想验证基于User.Identity.Name用户,并从SQL Server数据库样作用和最后的loggedIn日期等细节,等混合Windows身份验证与SQL Server自定义身份验证MVC3
登录我后应该授权同一用户进行后续调用而不触及数据库。
但是,我在初次登录时点击并加载用户信息,并将其存储在会话中。
这里是我的SQL表
ApplicationUser
- 用户ID - >窗户存放在这里的身份名称映射
- 显示名称
- 角色ID
- LastLoginDate
- IsActive
登录控制器逻辑
public ActionResult Login()
{
string userId = User.Identity.Name;
userId = userId.Substring(userId.IndexOf(@"\") + 1);
var key = "Roles." + userId;
var roles = HttpContext.Cache[key]
if (roles == null)
{
User user = AdminService.SelectUser(userId);
roles = new string[] { user.Role.RoleName };
HttpContext.Cache.Add(key, roles, null,
DateTime.Now.AddMinutes(HttpContext.Session.Timeout),
Cache.NoSlidingExpiration);
HttpContext.User = Thread.CurrentPrincipal = new
GenericPrincipal(User.Identity, roles);
HttpContext.Session["LoggedInUser"] = user;
}
}
另外我有下面的代码授权每个requestin MVC3
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string userId = User.Identity.Name;
userId = userId.Substring(userId.IndexOf(@"\") + 1);
var key = "Roles." + userId;
var roles = HttpContext.Cache[key];
if (roles != null)
{
HttpContext.Current.User =
Thread.CurrentPrincipal =
new GenericPrincipal(User.Identity, roles);
}
}
}
用户但我建议改变这种上面的逻辑,如我得到一个在访问存储在会话中的用户对象时发生问题。我不知道为什么它是这样的。
有没有人有其他可能的代码/逻辑做上述混合认证?
编辑:我在访问HttpContext.Session得到错误[ “与loggedInUser”]在某些其他控制器的方法。
我更新了我的问题。我将会话中的用户信息存储在稍后访问。但有时会发生错误。我的代码有些不好。我不知道发生了什么问题。我提到http://stackoverflow.com/questions/5947278/when-postauthenticaterequest-gets-执行你的旧回答,并试图按照 –
伟大的,这是我会推荐你的方法。 –
这很好。但使用与Windows身份验证相结合的FormsAuthenticationTicket不会产生任何问题,我认为。这样对吗? –