【问题标题】:Setting auth cookie timeout length based on role in ASP.NET根据 ASP.NET 中的角色设置身份验证 cookie 超时长度
【发布时间】:2011-02-21 00:22:05
【问题描述】:

我想让管理员登录的时间比普通用户长。我没有看到以编程方式或以基于角色的方式设置 cookie 超时的钩子。这在使用表单身份验证的 ASP 中是否可行?

【问题讨论】:

    标签: asp.net asp.net-mvc cookies forms-authentication roles


    【解决方案1】:

    片段:

         switch Role: 
         Case A: VARIABLE X = Y; BREAK;
         CASE B: VARIABLE X = Y2; BREAK;
         ..
    
         End switch
    
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, // Ticket version
            Username.Value, // Username associated with ticket
            DateTime.Now, // Date/time issued
            DateTime.Now.AddMinutes(VARIABLE X), // Date/time to expire
            true, // "true" for a persistent user cookie
            reader.GetString(0), // User-data, in this case the roles
            FormsAuthentication.FormsCookiePath);// Path cookie valid for
    
         // Encrypt the cookie using the machine key for secure transport
         string hash = FormsAuthentication.Encrypt(ticket);
         HttpCookie cookie = new HttpCookie(
            FormsAuthentication.FormsCookieName, // Name of auth cookie
            hash); // Hashed ticket
    
         // Set the cookie's expiration time to the tickets expiration time
         if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
    
         Response.Cookies.Add(cookie);
    

    【讨论】:

    • 非常清晰且乐于助人!谢谢!如果我使用 FormsAuthenticationTicket 重载只接收字符串用户名、bool IsPersitent 和 int 超时,我是否也会进行加密和分配给 cookie?
    • 我从这里了解到:msdn.microsoft.com/en-us/library/w04e17xz(v=vs.100).aspx 在备注中,FormsCookiePath 是自动设置的,所以加密等也会这样做。
    【解决方案2】:

    是的,你可以这样做。您需要手动生成身份验证票证,而不是让框架自动生成它。

    根据用户角色,您分配给工单的到期时间。

    This tutorial show how to generate the ticket manually.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-14
      • 2010-10-02
      • 2018-03-30
      • 2016-06-23
      • 2012-04-20
      • 2021-11-07
      • 2011-08-19
      • 1970-01-01
      相关资源
      最近更新 更多