Mixing Windows Authentication with SQL Server Custom Authentication MVC3

僤鯓⒐⒋嵵緔 提交于 2019-12-12 05:24:34

问题


I would like authenticate the user based on User.Identity.Name and get the other detail from SQL Server database like Role and last loggedin date, etc.

After login i should authorize the same user for subsequent calls without hitting database.

However i hit and load the user information at initial login and i stored in session.

Here is my SQL Table

ApplicationUser

  • UserId -> windows identity name mapping stored here
  • Display Name
  • RoleId
  • LastLoginDate
  • IsActive

Login Controller logic

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;
    }
}

Also i have the below code to authorize a user on each 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);
    }
}
}

But i advised to change this above logic, as i am getting an issue while accessing the User object stored in a session. I have no idea why it is like that.

Do any one have other possible code/logic to do the above mixed authentication?

Edit: I was getting error in accessing HttpContext.Session["LoggedInUser"] in some other controller method.


回答1:


as i am getting an issue while accessing the User object stored in a session.

You are not storing the info in a session. You are storing it in the Cache. That's your problem. The Cache is shared between all users of your application. So instead of using HttpContext.Cache you could use the HttpContext.Session.

Alternatively to using sessions and caches you could store thisinformation inside the UserData portion of the forms authentication cookie as I have illustrated in this post.



来源:https://stackoverflow.com/questions/14439497/mixing-windows-authentication-with-sql-server-custom-authentication-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!