【问题标题】:mvc4 add specific data to sessionmvc4 将特定数据添加到会话
【发布时间】:2013-10-29 17:50:38
【问题描述】:

我有一个登录表单。当用户登录时,他必须在两种类型中进行选择并发送用户名和密码。

我可以这样做,并且我可以连接到我的模型以验证用户身份。然后,如果他输入了正确的用户名和密码,我会这样做:

FormsAuthentication.SetAuthCookie(login.UserName, login.RememberMe);

但我需要一种方法来保存他的类型。我想我必须在会话中这样做,我说得对吗?如果是,请问如何?如果没有,最好的方法是什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 login session-variables


    【解决方案1】:

    如果您想使用会话,可以使用Session

    您可以在其中存储任何内容。因此,您可以根据需要存储整个登录对象。

    Session["user"] = yourUser;
    

    会话是一个好地方,因为它对每个用户都是独一无二的。

    如果您在 Web 应用程序中使用 MemberShip 类,您可以添加自定义字段,我认为这是解决您问题的最佳方法。请参阅此example 或此blog post。这不仅会将您的信息保存到用户的会话中,而且还会将此用户类型添加到数据库中。

    【讨论】:

      【解决方案2】:

      您可以在控制器中简单地使用 Session 对象:

      Session["usertype"] = yourType;
      

      但是,我会为这种信息存储使用自定义类,如果您有很多用户,您还应该重新设计此解决方案(重新考虑会话存储位置或在线用户数据位置)。

      【讨论】:

        【解决方案3】:

        这取决于。用户关闭浏览器后是否需要保存“类型”?因为如果你把它保存在会话中,下次他打开它就消失了。

        如果您确实需要保存它,最好使用 cookie。

        要添加 cookie,您可以执行以下操作:

        this.Response.Cookies.Add(new HttpCookie("my-cookie-name", myValueToSave));
        

        【讨论】:

        • “因为如果你保存在会话中,下次他打开它就没有了。”没那么简单。这取决于会话超时。用户也可以删除他们的 cookie。将 cookie 用于此类事情的另一个问题是,您将一遍又一遍地为每个 http 请求发送相同的 cookie。如果您希望它绝对持久,那么您应该使用持久存储。
        • 你说得对,事情没那么简单,但如果他需要它持久化,session 不是保存它的正确位置。似乎由于这与 Auth Cookie 结合使用,因此将其存储在 cookie 中可能更有意义。
        【解决方案4】:

        “保存他的类型”是什么意思?你是说他的角色吗?那么本质上用户在应用程序中的角色是什么?如果它是角色,那么也许将其存储在 Authcookie 中是正确的地方。您可以在身份验证 cookie 上添加其他值,甚至滚动您自己的 Authorize Attribute 以考虑其他值,然后这些值将在 User Principal 对象上可用 ` 公共接口 ICustomPrincipal : IPrincipal { 指导用户 ID { 获取;放; } 字符串名字 { 得到;放; } 字符串姓氏 { 得到;放; } 字符串电子邮件地址 { 获取;放; } 指导公司 ID { 获取;放; } }

        public class CustomPrincipal : ICustomPrincipal
        {
            public IIdentity Identity { get; private set; }
            public bool IsInRole(string role)
            {
                return false;
            }
        
            public CustomPrincipal()
            {
        
            }
        
            public CustomPrincipal(IIdentity indentity)
            {
                this.Identity = new GenericIdentity(indentity.Name);
            }
            public CustomPrincipal(string email)
            {
                this.Identity = new GenericIdentity(email);
            }
           public Guid UserID { get; set; }
           public string FirstName { get; set; }
           public string LastName { get; set; }
           public string EmailAddress { get; set; }
           public Guid CompanyID { get; set; }
           public string CompanyName { get; set; }
           public string JobTitle { get; set; }
        
        
        }`.
        
        
         public sealed class CustomAuthoriseAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                bool isAuthorized = base.AuthorizeCore(httpContext);
                if (!isAuthorized) return false;
        
                CustomPrincipal customPrincipal = null;
                HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
        
                if (authCookie != null)
                {
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    var serializer = new JavaScriptSerializer();
        
                    if (authTicket != null)
                    {
                        var serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
        
                        customPrincipal = new CustomPrincipal(authTicket.Name)
                        {
                            UserID = serializeModel.UserID,
                            FirstName = serializeModel.FirstName,
                            LastName = serializeModel.LastName,
                            CompanyID = serializeModel.CompanyID,
                            EmailAddress = serializeModel.EmailAddress,
                            CompanyName = serializeModel.CompanyName,
                            JobTitle = serializeModel.JobTitle,
        
                        };
                    }
                }
        
        
                         HttpContext.Current.User = customPrincipal;
        
                return isAuthorized;
            }
        }
        
        public  class CustomPrincipalSerializeModel
        {
          public Guid UserID { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string EmailAddress { get; set; }
          public Guid CompanyID { get; set; }
          public string CompanyName { get; set; }
          public string JobTitle { get; set; }
        
        }
        

        那么你的登录方法可能看起来像这样

         if (!membershipService.IsAccountLockedOut(loginModel.Email) &&
                    membershipService.Login(loginModel.Email, loginModel.Password))
                {
                    UserDto user = membershipService.GetUserDetail(loginModel.Email);
                    var cookieContext = new CookieContext();
                    cookieContext.SetAuthenticationToken(user);
                    //Need to check if user has reset thier password and needs to change it
                    if (!user.PasswordReset)
                    {
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("ChangePassword", "Account");
                    }
                }
        

        Set Authentication Method 看起来像这样

        public void SetAuthenticationToken(UserDto userDto)
            {
                string userData;
                string encTicket;
        
                var serializeModel = new CustomPrincipalSerializeModel();
                serializeModel.UserID = userDto.ID;
                serializeModel.FirstName = userDto.FirstName;
                serializeModel.LastName = userDto.LastName;
                serializeModel.EmailAddress = userDto.Email;
                serializeModel.CompanyID = userDto.CompanyID;
                serializeModel.CompanyName = userDto.Company;
                serializeModel.JobTitle = userDto.JobTitle;
        
                var serializer = new JavaScriptSerializer();
                userData = serializer.Serialize(serializeModel);
        
                var autTicket = new FormsAuthenticationTicket(1, userDto.Email, DateTime.Now,
                                                              DateTime.Now.AddMinutes(15), false, userData);
                encTicket = FormsAuthentication.Encrypt(autTicket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                cookie.HttpOnly = true;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        

        您需要在整个应用程序中与用户一起旅行的所有数据都在身份验证 Cookie 上可用,并且在您使用 CustomAuthorise 属性时在用户对象上可用

         [CustomAuthorise]
            [OutputCache(NoStore = true, VaryByParam = "*", Duration = 0)]
            public ActionResult Index()
            {
        
                var model = _someService.SomeFunction(User.CompanyID);  //Company ID is from Auth Cookie
                return View(model);
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-04
          • 1970-01-01
          • 2016-04-10
          • 2017-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多