0

我想验证基于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”]在某些其他控制器的方法。

回答

1

因为我在访问存储在会话中的用户对象时遇到问题。

您没有在会话中存储信息。您正在将其存储在缓存中。那是你的问题。缓存是在您的应用程序的所有用户之间共享的。因此,您可以使用HttpContext.Session而不是使用HttpContext.Cache

除了使用会话和缓存,您可以将此信息存储在表单身份验证cookie的UserData部分中,因为我有illustrated in this post

+0

我更新了我的问题。我将会话中的用户信息存储在稍后访问。但有时会发生错误。我的代码有些不好。我不知道发生了什么问题。我提到http://stackoverflow.com/questions/5947278/when-postauthenticaterequest-gets-执行你的旧回答,并试图按照 –

+0

伟大的,这是我会推荐你​​的方法。 –

+0

这很好。但使用与Windows身份验证相结合的Fo​​rmsAuthenticationTicket不会产生任何问题,我认为。这样对吗? –

相关问题