代码之家  ›  专栏  ›  技术社区  ›  Wyatt

基于ASP.NET中的角色设置身份验证cookie超时长度

  •  8
  • Wyatt  · 技术社区  · 14 年前

    我希望允许管理员登录的时间比普通用户长。我没有看到一个钩子可以通过编程或基于角色的方式设置cookie超时。这在使用窗体身份验证的ASP中是可能的吗?

    2 回复  |  直到 8 年前
        1
  •  7
  •   Adrian Toman Duncan_m    12 年前

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

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

    This tutorial show how to generate the ticket manually.

        2
  •  6
  •   Dov Miller    8 年前

    片段:

         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);