The ASP.NET Capsule #2: Login Programmatically With Forms Authentication
Hi all.
In this capsule, I’ll show you how to login a user using Forms Authentication but programmatically. The process is actually simpler than you might think.
If you know the username you can login the user with the following line of code:
1: FormsAuthentication.SetAuthCookie(UserName, false);
Now, the first parameter is obviously the username of the user you want to login, the second parameter is less known but very helpful. If you want to implement the famous “Remember Me” checkbox in a login form, the second parameter will help you, it instructs Forms Authentication to create a persistent cookie for the user thus providing the ability to “remember” the user the next time he/she opens the browser.
Set the second parameter to “false” if you want to discard the cookie when the browser closes, or to “true” to keep the cookie and remember the user the next time.
NOTE: although SetAuthCookie will issue an authentication ticket for the user (persistent or not), it will not know if the user is actually a registered and valid user for the website. For that we would need to implement some type of Membership system (like the ASP.NET Membership System) and validate the user prior to issuing a ticket with SetAuthCookie.
Hope it was informative.
Enjoy!!