Where to store logged user information on ASP.NET MVC using Forms Authentication?

前端 未结 4 1004
情深已故
情深已故 2020-12-23 21:34

I\'m using ASP.NET MVC and Forms Authentication on my application. Basically I use FormsAuthentication.SetAuthCookie to login and FormsAuthentication.Sig

4条回答
  •  情话喂你
    2020-12-23 22:18

    I actually like to use a CustomPrincipal and CustomIdentity which I set in the logon action method like

            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password) && _authService.IsValidLogin(username, password))
            {
                User objUser = _userService.GetUserByName(username);
                if (objUser != null)
                {
                    //** Construct the userdata string
                    string userData = objUser.RoleName + "|" + objUser.DistrictID + "|" + objUser.DistrictName + "|" + objUser.ID + "|" + objUser.DisplayName;
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, rememberMe.GetValueOrDefault());
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    Response.Cookies.Add(authCookie);
                    return RedirectToAction("Index", "Absence");
                }
                else
                {
                    return RedirectToAction("LogOn", "Account");
                }
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
    

    Then in the custom principal you can have methods that access specific information you passed in to the constructor like

    ((CustomIdentity)((CustomPrincipal)HttpContext.Current.User).Identity).DisplayName;
    

    where the DisplayName property is declared in the CustomIdentity class.

提交回复
热议问题