Tuesday, November 8, 2011

Use Membership for user management - Basics

In this article we shall discuss the membership feature in ASP.NET applications. Asp.net has reduced the development drastically by introducing this. Membership feature of Asp.Net drastically reduces the amount of code we have to write to authenticate users at our Web site. In this article we are going to develop User Management system membership class, and SqlMembershipProvider.

Membership feature of Asp.net provides a membership API that simplifies the task of validating user credentials. SqlMembershipProvider uses SQL Database for storing membership details.

Step1: Install Membership Database for SQLMembershipProvider.
To install Membership Database we have to log on to our server with an account that has authority to administer SQL server. After this open Visual Studio 2010 Command prompt.


Run following command
aspnet_regsql.exe -E -S localhost -A m

Where:
    -E indicates authenticate using the Windows credentials of the currently logged on user.
    -S (server) indicates the name of the server where the database will be installed or is already installed.
    -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Above command mainly generates database naming "aspnetdb" with following  schema structure and related stored procedures


* Please Note that Related stored procedures also get created with above command. These stored procedures get called internally from Membership provider. 

Step2: Configure Forms Authentication
Set following authentication mode in Web.config file
<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 
           protection="All" 
           timeout="30" 
           name="AppNameCookie" 
           path="/FormsAuth" 
           requireSSL="false" 
           slidingExpiration="true" 
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>

If so many options are not required we can simply use following Tag for authentication

<authentication mode="Forms">
      <forms loginUrl="Login.aspx" timeout="2880" />
    </authentication>

Add the following <authorization> element after the element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.


<authorization> 
   <deny users="?" />
   <allow users="*" />
</authorization>
  
Step 3: Configuring SQLMembership Provider
In Step 1, we created SQL Database for Membership Provider, in this step we will configure SQLMembership Provider in Web.config file.


<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
...
  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    <providers>
      <clear />
      <add 
        name="SqlProvider" 
        type="System.Web.Security.SqlMembershipProvider" 
        connectionStringName="MyConnectionString"
        applicationName="/"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="true"
        requiresUniqueEmail="true"
        passwordFormat="Hashed" />
    </providers>
  </membership>

Default passwordFormat is "Hashed", if we remove it from Configuration then by default Passwords are stored in Hashed format. We can change passwordFormat to Encrypted. (This is not the scope of this Article; I shall put another article for it.)

Step 4: Start using Membership class
Upto step 3 we were only doing configuration for using Membership class. After we done with step 3; whenever we use Membership class, if by default uses Database structure generated in Step 1. It internally manages all the Database calls.
e.g.
Membership.CreateUser("UserName","Password");
//This will create user in Database.
Check out following Membership APIs for user management in Asp.net.
MethodParametersNotes
CreateUserstring username–User name to create.

string password–Password for new user


string email–E-mail for new user.

string passwordQuestion

string passwordAnswer

bool IsApproved

object providerUserKey
Used to create a new user.
DeleteUserstring username–User to delete.

bool removeAllRelatedData
Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
FindUsersByNamestring usernameToMatch

int pageIndex

int pageSize
Returns a collection of users where the string parameter passed matches part of the username.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
FindUsersByEmailstring emailToMatch

int pageIndex

int pageSize
Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
GeneratePasswordint length

Int numberOfNonAlpha

NumericCharacters
Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
GetAllUsersint pageIndex

int pageSize
Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
GetNumberOfUsersOnlineNoneReturns a count of all the users who are currently online

The Active Directory provider does not implement this functionality
GetUsernameByEmailstring email–Email of user to lookup.Return a member's username.
UpdateUserMembershipUser user–Membership user to updateUpdates a member's properties; for example, an e-mail address.
ValidateUserstring username–User name to validate.

string password–User password to validate.
Validates a user's credentials. Returns true if the credentials are valid and false if they are not.


With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.
(Note: Above table is picked up from MSDN)

This is how we can use Membership class for User management in Asp.net using SQLMembershipProvider.

Submit this story to DotNetKicks

2 comments:

Unknown April 13, 2012 at 11:02 PM  

Hi...Your post really got me thinking man..... an intelligent piece, I must say. User management

denmas_yono June 21, 2012 at 7:55 AM  

I like this Tutorrial, nice!