根据ASP.NET中的角色设置auth cookie超时长度

时间:2010-05-18 17:16:24

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

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

2 个答案:

答案 0 :(得分:8)

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

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

This tutorial show how to generate the ticket manually.

答案 1 :(得分:7)

片段:

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