Enhancing Website Security with Membership Provider in Asp.Net

DZone 's Guide to

Enhancing Website Security with Membership Provider in Asp.Net

· ·
Free Resource

All of the websites are available whenever you connect to the internet, this is the ideal scenario for web world, but sometimes it isn’t always an appropriate design choice. Let’s take an example of an e-commerce website, where you need to provide a secure way for your customers to complete monetary transactions, or at subscription based sites that need to restrict people who haven’t paid a fee for that subscription. Even a public website may provide some features or services which shouldn’t be available for particular users. All of these examples require a security model, which conducts the proper security for the web application. Every development language provides a security model. Here we are talking about the ASP.NET platform for understanding the need of the authentication and authorization for the particular websites and implementing it with the help of Membership Class.  

The first step in implementation of security for a web application is understanding the security requirements. It is the crucial part because it is not a good strategy to build the same security model throughout the application whether the application needs it or not. Security doesn’t need to be complex but should be multilayered enough to protect user's privacy. 

Original Article found here

Membership is a layer of security model, provided by Microsoft in asp.net, which provides features of mainly three categories: 1) User Record Management – while using Membership features in ASP.NET, you don’t need to create any database for handling security purpose, instead of it; asp.net creates one for you and maintains catalogs of user information. 2) Security controls – Membership has its own security controls such as login, forgot password, create new user etc. so you need to design these control for your websites. 3) Role based security – Membership supports roles that mean you can provide different permissions to different types of people in the same application. Before continuing any further implementing Membership in your asp.net website you need to set authentication of application to ‘Forms’. Here is the code you can use to do so –

<system.web>  <authentication mode="Forms" /> </system.web> 

Now if you have decided to use Membership in your application, you need to create a database for the Membership, but if you are using SQL Server 2005 or higher version then you need not to do anything, your application will create a Membership Database for you inside the ‘App_Data’ subfolder of your website having name – ‘aspnetdb.mdf’. The default Connection String used by Membership is ‘LocalSqlServer’ which can be configured in ‘web.config’ file as follows –


    <clear />  
    <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS; Integrated Security=SSPI; initial catalog=aspnetdb" /> 

Now you need to configure Membership Provider in ‘web.config’ file to use its classes as follows –


<membership defaultProvider="MyMembershipProvider">  
         <add name="MyMembershipProvider" 
          type="System.Web.Security.SqlMembershipProvider" />  

Within the <membership> section, you can add multiple providers as child elements of the ‘<providers>’ section. In the previous code, you can see a valid configuration for the included ‘SqlMembershipProvider’. It’s important not to forget about the ‘defaultProvider’ attribute on the ‘<membership>’ element. This attribute indicates the membership provider that your application will use. Configured providers are shown in the ASP.NET web configuration when selecting the option Select a Different Provider for Each Feature in the provider configuration. Following is a table which describes the attributes of Membership Provider:


Property Description
name Specifies a name for the membership provider. You can choose any name you want. You can use this name later for referencing the provider when programmatically accessing the list of configured membership providers. Furthermore, the WAT will use this name to display the provider.
applicationName String value of your choice that specifies the name of the application for which the member-ship provider manages users and their settings. This setting allows you to use one membership database for multiple applications. Users and roles are always associated with an application. If you do not specify an application name, a root application name called “/” will be used automatically. More details are outlined after the table.
description An optional description for the membership provider.
passwordFormat Gets or sets the format in which passwords will be stored in the underlying credential store. Valid options are Clear for clear-text password storage, Encrypted for encrypting passwords in the data store (uses the locally configured machine key for encryption), and Hashed for hashing passwords stored in the underlying membership store.
minRequiredNonalphanumericCharacters Specifies the number of non-alphanumeric characters the password needs to have. This is an important part for the validation of the password and enables you to specify strength requirements for the passwords used by your users.
minRequiredPasswordLength Allows you to specify the minimum length of passwords for users of your application. This is also an important property for specifying pass-word strength properties.
passwordStrengthRegularExpression If the previously mentioned properties are not sufficient for specifying password strength conditions, then you can use a regular expression for specifying the format of valid passwords. With this option you are completely flexible in terms of specifying password format criteria.
enablePasswordReset The membership API contains functionality for resetting a user’s password and optionally sending an e-mail if an SMTP server is configured for the application.
enablePasswordRetrieval When set to true, you can retrieve the password of a MembershipUser object by calling its GetPass-word method. Of course, this works only if the password is not hashed.
maxInvalidPasswordAttempts Specifies the number of invalid validation attempts before the user gets locked. The default value of this setting is 5. In many cases, you’ll likely want to set this to a lower level depending on your security policy.
passwordAttemptWindow Here you can set the number of minutes in which a maximum number of invalid password or pass-word question-answer attempts are allowed before the user is completely locked out from the application. In that case, the user gets locked out, so the administrator must activate the account again. Again, the default value is ten minutes. Depending on your security policies, you might want to lower or raise the value.
requiresQuestionAndAnswer Specifies whether the password question with an answer is required for this application. This question can be used if the user has forgotten his password. With the answer he gets the possibility of retrieving an automatically generated, new password via e-mail
requiresUniqueEmail Specifies whether e-mail addresses must be unique for every user in the underlying member-ship store.

Membership Classes

Many methods of the Membership class accept an instance of ‘ MembershipUser’ as a parameter or return one or even a collection of ‘ MembershipUser’ instances. For example, by retrieving a user through the ‘ Membership.GetUser’ method, setting properties on this instance, and then passing it to the ‘ UpdateUser’ method of the Membership class, you can simply update user properties. The ‘ Membership’ class and the ‘ MembershipUser’ class both provide the necessary abstraction layer between the actual provider and your application. Everything you do with the Membership class depends on your provider. This means if you exchange the underlying membership provider, this will not affect your application if the implementation of the membership provider is complete and supports all features propagated by the ‘ MembershipProvider’ base class.

Retrieving Users from the Store

To retrieve a single user and a list of users through the Membership class from the membership store. You just need to create a simple page with a GridView control for binding the users to the grid, as follows:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Retrieve Users</title>
 <form id="form1" runat="server">
        <asp:GridView ID="UsersGridView" runat="server"
                <asp:BoundField DataField="UserName" HeaderText="Username" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
                <asp:BoundField DataField="CreationDate"
                                HeaderText="Creation Date" />
                <asp:CommandField ShowSelectButton="True" />

You can now add the following code to the ‘Page_Load’ event procedure for loading the users from the membership store and binding them to the grid:


public partial class _Default : System.Web.UI.Page 
     MembershipUserCollection _MyUsers; 
     protected void Page_Load(object sender, EventArgs e) 
          MyUsers = Membership.GetAllUsers(); 
          UsersGridView.DataSource = _MyUsers; 
          if (!this.IsPostBack) 

Creating and Deleting Users

Creating users is as simple as using the rest of the membership API. You can create users by just calling the ‘CreateUser’ method of the Membership class. Therefore, if you want to add the feature of creating users to your website, you can add a new page containing the necessary text boxes for entering the required information, then add a button, and finally handle the Click event of this button with the following code:


protected void ActionAddUser_Click(object sender, EventArgs e) 
         MembershipCreateStatus Status; 
         Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtUserEmail.Text, txtPwdQuestion.Text, txtPwdAnswer.Text, true, out Status); 
         StatusLabel.Text = "User created successfully!";
    catch(Exception ex) 
         Debug.WriteLine("Exception: " + ex.Message); 
         StatusLabel.Text = "Unable to create user!"; 

Validating Users

Last but not least, the Membership class provides a method for validating a membership user. If a user has entered his user name and password in a login mask, you can use the ‘ValidateUser()’ method for programmatically validating the information entered by the user, as follows:

if (Membership.ValidateUser(txtUserName.Text, txtPassword.Text)) 
      FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false); 
else { // Invalid user name or password message. } 

We can use Membership provider for all the web applications whether they are in asp.net or PHP, moreover Membership is available in Windows Application as well, we will discuss this topic further in next tutorials.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}