Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting auth cookie timeout length based on role in ASP.NET

I want to allow admins to be logged in for longer than normal users. I don't see a hook for setting the cookie timeout programmatically or in a role-based way. Is this possible in ASP using Forms Authentication?

like image 887
Wyatt Avatar asked May 18 '10 17:05

Wyatt


People also ask

What is the use of Formsauthentication SetAuthCookie?

The forms-authentication ticket supplies forms-authentication information to the next request made by the browser. With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.

How do I expire cookies in .NET core?

HttpOnly = true; options. Cookie. IsEssential = false; }); // Change cookie expiration from "until browser close" to 14 days services.

What is Aspxauth cookie?

This cookie is a 'session cookie' and tells us that you are actively using our website. .ASPXAUTH. The ASPXAUTH cookie is used to determine if a user is authenticated.


2 Answers

Yes, you could do that. You would need to generate the authentication ticket manually instead of letting the framework generate it automatically.

Depending the user role, the expiration you assign to the ticket.

This tutorial show how to generate the ticket manually.

like image 62
Claudio Redi Avatar answered Sep 27 '22 20:09

Claudio Redi


SNIPPET:

     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);
like image 45
Aseem Gautam Avatar answered Sep 27 '22 20:09

Aseem Gautam