.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Handling user authentication: introducing Membership API

Posted By:Manning       Posted Date: February 12, 2011    Points: 75    Category: ASP.NET    URL: http://www.dotnetspark.com  

The authors discuss Membership API, a set of programming API used to interact with membership features inside an ASP.NET application.

This article is taken from the book ASP.NET 4.0 in Practice. The authors discuss Membership API, a set of programming API used to interact with membership features inside an ASP.NET application.


Get 40% off any version of ASP.NET 4.0 in Practice with the checkout code dnspark40. Offer is only valid through www.manning.com.

Membership API, as its name suggests, is a set of programming API used to interact with membership features inside an ASP.NET application. Membership API is based on Provider Model Design Pattern.

The Provider Model is a variant on the Strategy Pattern, whereby the implementation details can be selected at runtime. As shown in figure 1, Strategy is an abstract type declaring a common interface, used by the ConcreteStrategy (the algorithm implementation), where Context uses the common interface to execute the algorithm implementation given by ConcreteStrategy and holds a reference to this concrete object.

Figure 1 The Provider Model Design Pattern is based on Strategy Pattern, so their diagrams are very similar. For each Strategy, one or more ConcreteStrategies exist.

In  Membership  API,  Membership class  from  System.Web.Securitcorresponds  to  the  Context,  where MembershipProvider class is the Strategy. Depending on the concrete implementation (the storage you want to query for membership information), you will have a specific class for the ConcreteStrategy: for SQL Server, this class is SqlMembershipProvider.

The advantage of this approach is that the API will never change and neither will the provider base class (the interface), and you can swap concrete implementations (the providers their selves) without changing anything else.
This  is  very  useful  especially when  you  are  building your  application from  scratch  because  it  lets  you concentrate on other aspects and have a building block ready to be used to implement a task that is repetitive and very similar from time to time.

Under the hood, Membership API is built on ASP.NET pipeline so it does leverage both FormsAuthentication and UrlAuthorization.

To move on with our ideal step-by-step guide of building a secure section in our web site, we need to start implementing a simple application using Membership API to grant access to logged-in user by implementing the common feature in an application, as registration and login are. At the end of this part we will have a completely working secure section added to our website.

Implementing a user login using Membership API

So, Membership API is what we need to use in order to add a login feature to our site. As the Provider Model Design Pattern is used here, all we need is to understand how to leverage this model to use the providers already available with ASP.NET and build a simple login system. Membership API aims to make you productive by letting you change the inner logic using a simple provider mechanism.


We want to build a secure section on our site using Membership API to grant access to our reserved area only to authenticated users.
We want to provide a complete experience so we will build user registration, password reminder/reset, and, obviously, user login.


Thanks to the Provider Model, this specific area in ASP.NET-a new feature from version 2.0-is very easy to implement.  Membership  API,  using  a  dependency  injection,  reads  the  configuration  from  the  web.config

configuration\system.web\membership\providers section  so  you  can  change  the  provider  without changing the code.
If you need to change the implementation, all you need to do is change the default provider used in web.config: API will not change and nor will the interface, and you do not need to alter any part of your code to reflect a different implementation.

This feature is very important when you are building applications targeting different customers: you can change the provider used from SQL Server to Oracle, if your customer needs it, and you are done: you do not have to change anything else regarding this particular aspect.

Membership API ships in ASP.NET with two providers:

§   SqlMembershipProvider-It supports SQL Server 7, 2000, 2005, and 2008 (even in Express/MSDE

§   ActiveDirectoryMembershipProvider-Specific for Active Directory use, in intranet.

For our example, we will use SqlMembershipProvider, since it is way more diffused to store the users in a SQL Server database than using Active Directory. Anyway, the approach is identical since they both are sharing the same base.
To start, we need to launch the aspnet_regsql.exe command line tool under .NET Framework directory (C:\Windows\Microsoft.NET\Framework\v4.0.30319\). This tool will build the database for us so we can store the users in SQL Server. In figure 2, you can see the wizard in action.

Figure 2 The aspnet_regsql.exe tool, when launched without other parameters, has a graphical wizard to configure the database. It could also be launched programmatically, with parameters to create the schema in unattended mode.

The typical user configuration in web.config to enable the SQL Server provider for Membership API can be seen in listing 1.

Listing 1 The SqlMembershipProvider web.config configuration
p defaultProvider="SqlServerMembership">

r />
d name="SqlServerMembership"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
#1 connectionStringName="SqlServer"  #2 enablePasswordRetrieval="false"
enablePasswordReset="true"  #3 requiresQuestionAndAnswer="false"
applicationName="/"  #4

requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />

#1 The provider to be used
#2 The provider connection string
#3 Password is hashed
#4 The application name
The default Membership provider for SQL Server is using a custom set of stored procedures and tables. If you already have a database in place, you need to use a custom provider.
The applicatioName attribute is important because the default provider for SQL Server is supporting multiple applications in the same database, and this is indicating the name of the current application. If this value is omitted, the default virtual directory path is used. In table 1, you can find the most used method associated to Membership class.

Table 1 Membership class most used methods

Nam Description
ChangePassword   To change the password of the specified user.
CreateUser   To create a new MembershipUser.
DeleteUser   Used to delete the specified user.
GetUse To get the specified MembershipUser, given the username.
ValidateUser   To validate username, and password, with a Boolean response.

The class members in Membership API will not be directly called in your code because they are part of the Framework, and they will remain the same. Thus, they are using the defined Membership provider specified in web.config, so the code can be predetermined. For that reason, ASP.NET contains a number of custom controls that are automating the corresponding scenarios, so you can take advantage of them without explicitly writing any code.

Let's take a look at very common scenarios, with the corresponding solutions using ASP.NET controls and
Membership API features.

Registering a new user

If you need to create a new user, you can use the CreateUserWizard control, as in listing 2.
Listing 2 Using the CreateUserWizard to create a new use

The CreateUserWizard control will add a simple wizard to create the user, as shown in figure 3.

Figure 3 The CreateUserWizard control will just display a list of fields to let the user register in our application. You can customize this control using a template.


Membership information is just about collecting a username, an email, and a password. So Membership API (and providers) only supports this kind of information.

You literally do not need to write a line of code to implement user registration since the magic is performed by this control, which will automatically invoke the CreateUser method of the Membership class (that will use the corresponding concrete provider specified in web.config).

Implementing user login

As for the previous example, the login is performed by a specific control, the Login control: under the hood, this control is using the authentication settings in web.config, in this case, FormsAuthentication. In the following snippet you can find the corresponding markup used to display a login form:

This control is very simple to use, and very powerful since it will automatically perform the associated action. You can find a screenshot of the control in figure 4.

Figure 4 The Login control will render a simple pair of fields. The user will enter username and password and, if they are correct, will log in to the application.

This control, in its simplicity and power, probably is the most tangible sign of Membership API force: just write a single line of markup in your page and it will automatically take care of a lot of tasks, such as validating the user input, perform the calls to the provider, and notify the user.

Recovering or changing the user password

If you need to reset the user password, there is a specific control, the PasswordRecovery.  To change the user password while logged in, a ChangePassword control is available. In the following snippet, you can find the corresponding markup necessary to implement the password recovery feature:

PasswordRecovery control supports body and subject personalization for the generated email. More information can be found on the documentation on MSDN at http://msdn.microsoft.com/en-us/library/ms1783311.aspx.


Membership API is really about the controls that ASP.NET provides. The default providers will work in many situations but, even if you need to target different storage or a complex logic, the approach remains the same:

thanks to Provider Model, all you need is to change the concrete implementation (the provider) and not the rest of the code.
If you are comfortable with the default providers, you can insert this type of feature in your applications with little effort and no code at all in really a couple of minutes. And this is very cool since this code is tested and developed by Microsoft to be safe, robust, and scalable.
To proceed in our analysis, other controls may be of interest to complete the picture. Let's take a look at them.

Other security controls
There are  other security controls that  can  be  used  to  enhance the  features related to  authentication and authorization in ASP.NET and increase your productivity. In table 2 you can find a list of controls you can use in ASP.NET.

Table 2 ASP.NET security controls.

Nam Description
Login   To provide the login form and authenticate the user.
LoginView To provide an alternate view for anonymous and logged users.
PasswordRecovery   To recover user password.
LoginStatus   To show a login link when the user is anonymous or a logout link when the user is logged in.
LoginName   To display the current username.
CreateUserWizard To create a new user.
ChangePassword   To change the password of the current logged in user.

By using these controls you can write less code to implement the corresponding features.


Thanks to the Provider Model, Membership API provides an extremely powerful approach to very repetitive tasks, such as user management. Thanks to the built-in security controls in ASP.NET, this is even more easily integrated in applications, since all the work is performed behind the scenes.

ASP.NET 4.0 in Practice

Daniele  Bochicchio, Stefano  Mostarda, and  Marco  De
MEAP Began: February 2010
Softbound print: March 2011 (est.) | 425 pages
ISBN: 9781935182467

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend