ASP.NET MVC Framework: Forms Authentication MVCToolkit and MembershipControllerBase
by David Hayden, Florida ASP.NET Developer
Fredrik Norman has a post on using the ASP.NET MVC Framework with Forms Authentication, ASP.Net MVC Framework - Using Forms Authentication, which got me thinking about how I handled user creation and logon using forms authentication in my sample ASP.NET MVC Application:

Where Fredrik rolled his own controller and called into the Membership Provider:
public class LoginController : Controller
{
[ControllerAction]
public void Login(string userName, string password,
string ReturnUrl)
{
if (this.IsValidLoginArgument(userName, password))
{
if (Membership.ValidateUser(userName, password))
this.RedirectFromLoginPage(userName, ReturnUrl);
else
this.ViewData["LoginFaild"] = "Login faild!
Make sure you have entered the right user
name and password!";
}
RenderView("Login");
}
// ...
}
I went ahead and took advantage of the MembershipControllerBase Class that someone added to the MVCToolkit. Here we can see it using Reflector:

It already has the appropriate Controller Actions and/or functionality for handling Login, Logout, Authenticate, etc. I just derived my UserController from it to handle Controller Actions like New and Create:
public class UserController : MembershipControllerBase
{
[ControllerAction]
public void New()
{
RenderView("New");
}
[ControllerAction]
public void Create()
{
User user = new User();
user.UpdateFrom(Request.Form);
Membership.CreateUser(user);
RedirectToAction(new { Action = "Login" });
}
}
User validation, creation, and all other Membership Related Functionality is done in the Custom Membership Provider via LINQ To SQL wrapped using the Repository Pattern:
public override bool ValidateUser(string username, string password)
{
User user = Repository<User>
.Find(u => u.Username == username &&
u.Password == password).SingleOrDefault();
return user != null;
}
Either way, there is a nice MembershipControllerBase Controller in the MVCToolkit that I would love to see updated and made more mature so that we can continue to leverage it in our ASP.NET MVC Framework Applications.
Hope this helps.
Author: David Hayden, Florida ASP.NET Developer
Site: http://www.davidhayden.com/
Recent ASP.NET MVC Tutorials: