Hi,
We are using the ASP.NET Portal starterkit as the basis of our current project. It contains form authentications and provides a login screen and an option to automatically login next time.
When a user selected the remember his credentials between different sessions, the only way to turn off this option is to use the log off option of the portal. Now suppose you want to control this behaviour by providing an option somewhere in your webpage that turns on/off the automatic login for the current user. Then the big question is, how do you know when a user was authenticated by a manual or an automatic login.
We'll get to the answer right away, but first some background info on the authentication system. Because a lot of info already exists, I'm just focussing on some important parts for this post. Basically, the difference between an manual and automatic login is wether or not the authentication cookie (default cookie name = ".ASPXAUTH") is persisted or not. Suppose you logged in manually, then the authentication cookie will be a session (in memory) cookie. When logged in automatically, it will be a persistend cookie (stored on the harddisk). When you log off, a FormsAuthentication.SignOut(); will be executed, removing any session/persistend cookie.
So, in order to know if it is a session or persistend authentication cookie, we need to use the Identity object from the User property of the current context (System.Web.HttpContext). Because we are working in the Portal with forms authentication, we need to type cast this identinty to a FormsIdentity:
FormsIdentity identity = (FormsIdentity)Context.User.Identity;
This class contains information about the Authentication Ticket, and it is this ticket where you can read if it was persisted or not (read, automatic login or manual):
bool automaticLogin = identity.Ticket.IsPersistent;
With this boolean, you can go ahead and implement an option that displays if automatic login is turned on/off.
Finally, when the user logged in manual, you can still force an automatic login via this method call:
FormsAuthentication.SetAuthCookie(identity.Name, true);
Note that the last param must be true, to indicate a presistend cookie.
(PS: thx Wesley, for your tip here)
- Erik