04 November 2013

ASP.NET - A basic authentification system

The simplest login system for ASP.NET (MVC) works by simply doing something like this:
HttpContext.Current.Session["User"] = user;
If Session["User"] yields NULL, your not logged in, otherwise you are. While this works, it has an annoying consequence: while you're working on the application, and you rebuild, the session gets lost and you have to log in every time you want to test. This can be remedied like this: First, add the following to the system.web section of the Web.config:
<authentication mode="Forms">
  <forms cookieless="UseCookies" loginUrl="/Home/Login" name="BFWauth" timeout="10512000" slidingExpiration="true" />
</authentication>
Second, in the same code that assigns Session["User"], add this:
System.Web.Security.FormsAuthentication.SetAuthCookie(user.Id.ToString(), false);
The user ID you put in there will be persisted even when the session is reset. Third, to know whether the user is logged in use:
if(HttpContext.Current.User.Identity.IsAuthenticated) { ...
The user ID is available here:
int userId = HttpContext.Current.User.Identity.Name.ToInt(); //ToInt() is an extension of mine.
User user = GetUser(userId); //This one's obvious.
You can now rebuild your application without being logged out. Life just got a little bit better.