Mixing Windows Authentication with SQL Server Custom Authentication MVC3

Xion Blueraven

New Member
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 TableApplicationUser
  • UserId -> windows identity name mapping stored here
  • Display Name
  • RoleId
  • LastLoginDate
  • IsActive
Login Controller logic\[code\]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; }}\[/code\]Also i have the below code to authorize a user on each requestin MVC3\[code\]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); }}}\[/code\]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.
 
Back
Top