Asp.net

根據 ASP.NET 中的角色設置身份驗證 cookie 超時長度

  • May 19, 2016

我想讓管理員登錄的時間比普通使用者長。我沒有看到以程式方式或以基於角色的方式設置 cookie 超時的鉤子。這在使用表單身份驗證的 ASP 中是否可行?

是的,你可以這樣做。您需要手動生成身份驗證票證,而不是讓框架自動生成它。

根據使用者角色,您分配給工單的到期時間。

本教程展示瞭如何手動生成票證。

片段:

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

引用自:https://stackoverflow.com/questions/2859474