Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set the Authentication Ticket manually when using the ASP.NET Login Control?

I am using the ASP.NET login control. I want to be able to set the timeout for Forms Authentication individually for each user (instead of globally in the web.config). From what I understand the only way to do this is to set the timeout on the AuthenticationTicket manually. Is there a way to do this when using the Login Control? It seems to me that the Login Control abstracts away all of this. I am hoping that there is some way to continue using the Login Control, but also have the ability to set the FormsAuthentication timeout individually for each user.

Thanks, Corey

like image 513
Corey Burnett Avatar asked Mar 11 '11 19:03

Corey Burnett


2 Answers

MSDN says:

The LoggedIn event is raised after the authentication provider checks the user's credentials and the authentication cookie is queued to send to the browser in the next response. Use the LoggedIn event to provide additional processing, such as accessing per-user data, after the user is authenticated.

So this event seems to be the right place to replace cookies. Firstly, the cookie need to be retrieved and decrypted:

HttpCookie authCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket oldAuthTicket = 
    FormsAuthentication.Decrypt(authCookie.Value);

right after this, the new authentication ticket based on just extracted should be created:

FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(
    oldAuthTicket.Version,
    oldAuthTicket.Name,
    DateTime.Now,
    DateTime.Now.Add(timeoutForUser),
    oldAuthTicket.IsPersistent,
    oldAuthTicket.UserData,
    FormsAuthentication.FormsCookiePath
);

timeoutForUser here is a TimeSpan value that holds the session timeout for the user.

And finally, the old cookie in the response should be replaced with the new one:

string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
authCookie = 
    new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Set(authCookie);

This should do the trick.

like image 54
Oleks Avatar answered Sep 22 '22 06:09

Oleks


The login control has LoggingIn and LoggedIn events that you could use to handle the authentication yourself.

You can cancel the login process in the LoggingIn event by setting e.Cancel = True and then create a ticket manually using new new FormsAuthenticationTicket(...)

like image 28
Geoff Appleford Avatar answered Sep 22 '22 06:09

Geoff Appleford