2013-04-05 26 views
1

例如,如果用户登录,存储用户ID和/或他/她的角色/组的最佳方法是什么?显而易见的方法是Cookie和会话?还有其他的选择如何在整个asp.net mvc(剃须刀3)应用程序中存储值?

+0

如果你想存储每个用户的价值,我认为这些是最好的选择 – pollirrata 2013-04-05 15:50:38

+0

我不完全遵循,你能给我一个例子吗? – Chaka 2013-04-05 15:54:35

+0

我在答案中添加了更多详细信息... – pollirrata 2013-04-05 16:00:27

回答

0

至少,使用Forms Authentication可以将用户ID和角色放在Formst Auth票证中。

Here'a的我是如何做的一个例子:

public static HttpCookie CreateCookie(IUserIdValue userId, string name, IEnumerable<int> group, bool isPersistent = false) 
    { 
     var user = new AuthenticationTicketData() { Groups = @group, UserId = userId }; 
     var ft = new FormsAuthenticationTicket(2, name, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), 
               isPersistent, user.Pack()); 
     var ck = new HttpCookie(FormsAuthentication.FormsCookieName) 
        { 
         Value = FormsAuthentication.Encrypt(ft), 
         Path = FormsAuthentication.FormsCookiePath, 
         Domain = FormsAuthentication.CookieDomain 
        }; 
     if (isPersistent) 
     { 
      ck.Expires = DateTime.Now.Add(FormsAuthentication.Timeout); 
     } 
     return ck; 
    } 


public static string Pack(this AuthenticationTicketData data) 
    { 
     if (data == null) throw new ArgumentNullException("data"); 
     return String.Format("{0};{1}",PackUserId(data.UserId),string.Join(",",data.Groups)); 
    } 

    static string PackUserId(IUserIdValue uid) 
    { 
     if (uid == null) throw new ArgumentNullException("uid"); 
     var tpn = uid.GetType().GetFullTypeName(); 
     return String.Format("{0}|{1}",tpn,uid.ToString()); 
    } 

public static HttpCookie SetAuthCookie(this HttpResponse response,IUserIdValue userId, string name, IEnumerable<int> group, bool isPersistent = false) 
    { 
     var ck = CreateCookie(userId, name, group, isPersistent); 
     response.AppendCookie(ck); 
     return ck; 
    } 

另一种选择是保留用户会话在数据库中(没有联系到会议),就像一个表(GUID,用户名,用户ID ,角色expireAt)。但是,如果您想要跟踪用户何时登录/注销,或者您是否使用自己的身份验证(而不是表单身份验证),则此方法更合适。

+0

感谢您的示例和说明! – Chaka 2013-04-08 12:45:06

0

如果你想存储每个用户的价值,我会议是最好的选择。会话是在每个用户/浏览器的基础上创建的。每个用户都有他/她自己的会话对象,这样您就可以在应用程序之间保留用户角色信息,直到会话结束。

我绝对不会建议将用户安全信息存储在cookie中,因为这会在您的应用程序中造成很大的安全漏洞。