将Windows身份验证与SQL Server自定义身份验证MVC3混合使用

时间:2013-01-21 13:15:23

标签: asp.net asp.net-mvc asp.net-mvc-3 session windows-authentication

我想基于User.Identity.Name对用户进行身份验证,并从SQL Server数据库获取其他详细信息,如角色和上次登录日期等。

登录后,我应该授权同一个用户进行后续调用,而无需点击数据库。

但是,我在初次登录时点击并加载用户信息,然后存储在会话中。

这是我的SQL表

ApplicationUser

  • UserId - > windows身份名称映射存储在这里
  • 显示名称
  • 角色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;
    }
}

此外,我还有以下代码在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);
    }
}
}

但我建议更改以上逻辑,因为我在访问存储在会话中的User对象时遇到问题。我不知道为什么会这样。

是否有任何人有其他可能的代码/逻辑来执行上述混合身份验证?

编辑:我在其他控制器方法中访问HttpContext.Session [“LoggedInUser”]时遇到错误。

1 个答案:

答案 0 :(得分:1)

  

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

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

,而不是使用HttpContext.Session

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

相关问题