Data Management

Secure ASP.NET 2.0 sites with Membership API

Beginning with ASP.NET 2.0, the Membership API was added to simplify adding security to a Web application. Tony Patton explains out how to use the Membership API with a SQL Server backend.

 

Most Web applications need to be secure because the apps allow users to sign up and log in and out of the site. Web application security is used to control access to all or part of a site.

Beginning with ASP.NET 2.0, the Membership API was added to simplify adding such security to a Web application. Find out how to use the Membership API with a SQL Server backend.

Essentials

Prior to version 2.0, .NET allowed developers to implement site security by providing a way to use Windows authentication, as well as a forms-based model. An issue with these approaches is the amount of development work that's necessary to get them working.

In ASP.NET 2.0, the Membership API has been added; it takes over where the forms-based approach ends. The Membership API also allows you to create, delete, and edit user properties. It includes two standard Membership providers that allow you to integrate with Active Directory or utilize a SQL Server backend. You may develop a custom provider to use with the Membership API as well.

Programming

The Membership API is available with the Membership class in the System.Web.Security namespace. It exposes the following methods for working with site users:

  • CreateUser: Allows you to create a new user.
  • DeleteUser: Allows you to delete a user.
  • FindUserByEmail: Allows you to find users with a particular e-mail address.
  • FindUsersByName: Allows you to find users with a particular username.
  • GeneratePassword: Allows you to generate a random password.
  • GetAllUsers: Returns all users.
  • GetNumberOfUsersOnline: Returns all users currently on the site.
  • GetUser: Allows you to find a user by username.
  • GetUserNameByEmail: Allows you to find a user by e-mail address.
  • UpdateUser: Allows you to update a user.
  • ValidateUser: Allows you to validate a user and password. ValidateUser is used to log a user onto the site.

These methods offer everything necessary to provide basic site security.

Using SQL Server as the backend data store

SQL Server is the default Membership provider; however, it does require setup to make it work. The.NET Framework includes a command-line tool (aspnet_regsql.exe) for adding the necessary database objects. The tool is available in this default directory:

C:<windows dir>Microsoft.NETFramework<version>aspnet_regsql.exe

When this tool runs without command-line parameters, a wizard guides you through setup. Basically, you choose the database server and the database to use. Then, a number of tables, views, and stored procedures are added to the database; these are used by the Membership API.

With the database set up, you may use it in your code as the data provider for membership services. The database connection string and the membership settings are configured in the application's web.config file.

The database connection string is defined in the connectionStrings element. The following example connects to an instance of SQL Server 2005 using SQL Server security:

<connectionStrings>

<add name="Test" connectionString="Data Source=TestServer;User ID=Chester;Password=Tester;Initial Catalog=MembershipTest;"/>

</connectionStrings>

Other sections are added to enable the Membership API. First, the authentication element (which is contained in the system.web element) is set to Forms. Next, the membership element is added (under system.web). It contains the providers element, which is mapped to the database connection string in my example -- it uses the name assigned to the connection string.

<authentication mode="Forms" />

<membership defaultProvider="TestProvider">

<providers>

<add name="TestProvider"

type="System.Web.Security.SqlMembershipProvider"

connectionStringName="Test" />

</providers>

</membership>

(To conserve space, this snippet only contains a portion of the complete web.config.)

Now with the backend connections set up, it can be used in an application.

Combining with Login controls

A great aspect of the Membership API is that the Login controls available within Visual Studio 2005/2008 are designed to work with it. You can easily drop one of the controls on an ASP.NET Web Form and tie it to a membership provider defined in the web.config file. These login controls include the following:

  • Login: Provides username and password textboxes for user logon. An error message is displayed if the logon fails. The ValidateUser method is used to check the user against the database.
  • LoginView: Retrieves a user's login status. LoginView uses this status to display content (defined in control) regardless of whether a user is logged in.
  • PasswordRecovery: Provides the functionality to retrieve or reset a user's password based on their username.
  • LoginStatus: Detects the user's authentication status and displays the appropriate login/logout option.
  • LoginName: Displays the currently authenticated user's name on the page. No value is displayed if the user is not logged on.
  • CreateUserWizard: Provides an interface for registering a user on the site. By default, it collects username, password, e-mail address, and validation question. It can be extended to include more fields and steps within the process.
  • ChangePassword: Allows the user to change their current password.

As an example, the following code snippet shows how the CreateUserWizard control may be used on an ASP.NET Web Form. The MembershipProvider attribute is set to the value assigned to the provider in our web.config file.

The WizardSteps allows you to customize the steps in the registration process -- that is accomplished in the following example with the message that is displayed upon successful registration (asp:CompleteWizardStep element). You may define additional steps as well.

<asp:CreateUserWizard

ID="CreateUserWizard1"

runat="server"

MembershipProvider="TestProvider">

<WizardSteps>

<asp:CreateUserWizardStep runat="server">

</asp:CreateUserWizardStep>

<asp:CompleteWizardStep runat="server">

</asp:CompleteWizardStep>

</WizardSteps>

</asp:CreateUserWizard>

All of the controls are easily tied to a membership provider, so it's simple to use the controls in a Web application without any code. Another good example is the LoginStatus control, which allows you to display custom messages according to a user's status.

<asp:LoginStatus

ID="LoginStatus1" runat="server"

LogoutText="Not logged in"

LoginText="Not Logged in" />

Easily secure your application

One of the goals with new releases of the .NET Framework is to simplify common programming chores. Providing site security via registration and logon is a common aspect of most Web applications. The Membership API provides methods for providing this functionality, and these methods are tied to the Login controls available for use on ASP.NET Web Forms.

What ASP.NET 2.0 features simplify your projects? What features would you like to see added to ASP.NET? Share your thoughts with the Web Developer community.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

11 comments
DukeCylk
DukeCylk

Is this the same facility that is then accessed through Visual Studio and with the Website Solution open and the web project selected, then under the menu bar selection you chose Website>ASP >net Configuration? And then the localhost web page displays the ASP.net Web Site Administration Tool? From there you select the Security Tab and are supposed to be able to set up all your users et al? At that point I am greeted with the error that there is a problem with my selected data store. I have read all the blogs and forums and have been debugging this for the better part of 2008 (OK, not all year, but when I get the chance to work on it) and to no avail have not been able to get it to find the data store I have supposedly set up on the server with the aspnet_regsql.exe. The Server (using SQL Server 2005 Express) is also hosting my website (VB, and ASP.net)...it is a Windows 2000 SP4 (implicitly IIS 5.0).

amitsjwn
amitsjwn

It's nice that you have all of the scattared information under the one roof. Keep on doing such type of work in the future.

MadestroITSolutions
MadestroITSolutions

The one thing I absolutely hate about it is the fact that you can only use the administration tool in your development environment, so you still end up coding interfaces for administrative purposes. Another thing worth mentioning is that this is meant to handle the authentication/authorization portion ONLY. People tend to think this is a complete solution for keeping people's profiles among other stuff. This feature stores information on a per-application basis so it is meant to be a separate block. What I do in my case is I keep it as a separate database usable by all applications and store the rest of the user information in another "specialized" application database. The only caveat with this is referential integrity, but then again, more times than not you don't want to set foreign keys on user IDs. Aside from that, it does save a lot of time. My two cents. Great article by the way. It would be nice if you could go a little bit more in depth in a future one.

ahmad_mohamads
ahmad_mohamads

Its a great Idea to Secure ASP.NET 2.0 sites with Membership API , but I wonder why SSL and portforwarding (tunneling ) is not used for web sites, is it difficult or impossible.

hychi
hychi

If you use shared hosting, deploy the membership database can be a burden. Overall I found the controls also lack flexibility. Maybe good for Intranet, enterprise, complex user management.

danny
danny

You probably meant to recommend using this tool instead of regiis: Aspnet_regsql.exe

aspatton
aspatton

Yes, you are correct, thank you for pointing it out.

olawumi
olawumi

I have tried this successfully a couple of times using Visual Web Developer Express. I got a rude shock when i tried to host a membership and roles enabled site, its not even a third as simple, in fact I could not get it work. I am also aware that its possible to use access as the Role Provider, any tip on this and handling live projects.

manishc108
manishc108

Thank you Tony. The article was brief but very meaningful. I have Membership provider in my project. It really does help in simplying common programming tasks. The functionalities exposed via the Membership API's coupled with the SQL and Active Directory providers and Login controls (Login,Change password and CreateUserWizard); really help to cut down the common programming chores required in projects.

Justin James
Justin James

Tony, thanks for the piece. The membership system is one of my favorite items in .Net, since it releives the burden of having to "boilerplate" this code. J.Ja

aspatton
aspatton

Yes, a great addition to the framework - saves lots of time.

Editor's Picks