ASP.NET 2.0 Roles, Memberships and Users
I admit, after attending the Visual Studio 2005 Launch this fall and hearing that the .NET 2.0 framework would decrease the amount of code written by 70%, I was more than doubtful. My programmer snobbery kicked in, and I was instantly scoffing at this type of claim. From the clients and colleagues I've talked with, a lot of companies have adopted this type of thinking as well, and some are dragging their feet instead of starting to develop apps using the 2.0 Framework. Maybe its time to take another look...
One example I recently implemented really showed how 2.0 can live up to its bold claims. Working with ASP.NET 2.0's Membership and Roles classes really made user management simple...here's a quick sample of how I can add new users, validate their credentials, add (or remove) them to roles, and authenticate them...all in very little code:
private void CreateNewMarketingUser(string username, string password, string email)
{
// Create a new user
MembershipCreateStatus status;
Membership.CreateUser(username, password, email, DEFAULT_PASSWORD_QUESTION,
DEFAULT_PASSWORD_ANSWER, true, out status);
// Verify Creation
if (status != MembershipCreateStatus.Success)
{
// Creation failed
throw new Exception(status.ToString());
}
else
{
// Authenticate this user
if (Membership.ValidateUser(username, password))
{
// Add new user to desired role
if (Roles.RoleExists(CommonBase.ROLE_MARKETING))
{
Roles.AddUserToRole(username, _
CommonBase.ROLE_MARKETING);
}
// Success, redirect to originally desired destination
// (assuming user was bounced to this page
// for not being authenticated)
// This also adds the authentication cookie specified in
// web.config to user
FormsAuthentication.RedirectFromLoginPage( _
username, chkPersistentCookie.Checked);
}
else
{
// Validation failed
throw new Exception("A new user could not be validated.");
}
}
}
If you are new to Memberships and Roles, be sure to set up your SQL database to support these functionalities, by running the following command from your Visual Studio command prompt: aspnet_regsql. This will create the necessary database entities to support roles, memberships, personalization, profiles and more.
I found that applying these new techniques directly really enhanced my code and gave me all the flexibility I needed. 2.0 also comes with 7 new Login controls, which out of the box support login, password recovery, user status views, and more. These controls take advantage of the APIs described above, and can really get your app out of the gate quickly.