ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.

You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

Let’s talk about password encoding and decoding and take the opportunity to introduce the Unit Of Work Pattern used to insert and retrieve data.

There exists a sequence of hash functions SHA-0, SHA-1, SHA-2 and the most recent SHA-3.

SHA-3, is a new cryptographic hash function that has been selected by NIST in October 2012 following a public competition launched in 2007, this because the weaknesses discovered on MD-5 and SHA-1 let fear fragility SHA-2 is built on the same schéma. It has variations that can produce hashes 224, 256, 384 and 512 bits. It is built on a different principle from that of MD5, SHA-1 and SHA-2 functions.

So in our tutorial, we will use the SHA-3 512 bits,

For this, it is not intended to replace SHA-2, which is at present not been compromised by a significant attack, but to provide an alternative response to attacks against MD5 possibilities standards SHA-0 and SHA-1.

A. Unit Of Work Pattern

We are using the default ASP.NET Membership database, so execute the script if it does not exist in your test database server, please see our tutorial

Generate the model and classes from membeship database (Model.Context.tt, Model.Entities.tt and Model.mapping.tt ) . If you are newly in Entity Framwork, please read our tutorial Introduction to entity framework Code first

We will use the DBContextFactory interface to handle multiple database or schemas, for example if a database contains multiple schemas, we will have the opportunity to work with multiple schemas within a single context.

Lets create a IUnitOfWork interfaceand implement it

IUnitOfWork interface will be used only to get Repositories, save context and finally dispose objects

B. Implementation of MembershipProvider

Our CustomMembershipProvider derives from MembershipProvider

The first thing we are doing is to override Initialize(string name, NameValueCollection config) so as to get config parameters and also get ApplicationId or create it if does not exist

In cryptography, a salt is random data that are used as an additional input to a one-way function that hashes a password or passphrase. The primary function of salts is to defend against dictionary attacks and pre-computed rainbow table attacks.

A new salt is randomly generated for each password. In a typical setting, the salt and the password are concatenated and processed with a cryptographic hash function, and the resulting output (but not the original password) is stored with the salt in a database. Hashing allows for later authentication while defending against compromise of the plaintext password in the event that the database is somehow compromised.

Now, to << decode >> the password (if one can speak of decoding) we can simply hash the password provided by the user with the basic salt stored on database and compare the resulting hash with the hash stored in the database.

So one and only the user knows the password. If any one else can discover the password then we are the victim of a successful attack.

The validate function can look like this

Try it :

public override bool ValidateUser(string username, string password)
{
// Get the user so as to find Salt and Hashed Password
aspnet_Users user = new MemberShipService().GetUser(username, _applicationId);

if (user != null)
{
// hash the password provided by the user with the basic salt stored on database and compare
// the resulting hash with the hash stored in the database

ASP.NET includes a tool for installing the SQL Server database used by the SQL Server providers, named Aspnet_regsql.exe. The Aspnet_regsql.exe tool is located in the drive:\WINDOWS\Microsoft.NET\Framework\versionNumber folder on your Web server. Aspnet_regsql.exe is used to both create the SQL Server database and add or remove options from an existing database.

You can run Aspnet_regsql.exe without any command line arguments to run a wizard that will walk you through specifying connection information for the computer running SQL Server and installing or removing the database elements for all the supported features. You can also run Aspnet_regsql.exe as a command-line tool to specify database elements for individual features to add or remove.

Note

The database elements that are installed in the feature database will always be owned by the SQL Server database owner account (dbo). In order to install the feature database, a SQL Server login must be permitted to the db_ddladmin and dd_securityadmin roles for the SQL Server database. However, you do not need to be a system administrator for the SQL Server in order to install the feature database.

To run the Aspnet_regsql.exe wizard, run Aspnet_regsql.exe without any command line arguments, as shown in the following example:

C:\WINDOWS\Microsoft.NET\Framework\<versionNumber>\aspnet_regsql.exe

You can also run the Aspnet_regsql.exe tool as a command-line utility. For example, the following command installs the database elements for membership and role management on the local computer running SQL Server:

aspnet_regsql.exe -E -S localhost -A mr

The following table describes the command line options supported by the Aspnet_regsql.exe tool.

Option

Description

-?

Prints Aspnet_regsql.exe tool Help text in the command window.

-W

Runs the tool in wizard mode. This is the default if no command line arguments are specified.

-C connection string

The connection string to the computer running SQL Server where the database will be installed, or is already installed. This option is not necessary if you only specify the server (-S) and login (-U and -P, or -E) information.

-S server

The name of the computer running SQL Server where the database will be installed, or is already installed. The server name can also include an instance name, such as .\INSTANCENAME.

-U login id

The SQL Server user id to log in with. This option also requires the password (-P) option. This option is not necessary if you are authenticating using Windows credentials (-E).

-P password

The SQL Server password to log in with. This option also requires the login id (-U) option. This option is not necessary if authenticating using Windows credentials (-E).

-E

Authenticates using the Windows credentials of the currently logged-in user.

-d database

The name of the database to create or modify. If the database is not specified, the default database name of « aspnetdb » is used.

-sqlexportonlyfilename

Generates a SQL script file that can be used to add or remove the specified features. The specified actions are not performed.

-A all|m|r|p|c|w

Adds support for one or more features. The following identifiers are used for ASP.NET features.

IdentifierAffects

allAll features

mMembership

rRole management

pProfile

cWeb Parts personalization

wWeb events

Feature identifiers can be specified together or separately, as shown in the following examples.

aspnet_regsql.exe -E -S localhost -A mp

aspnet_regsql.exe -E -S localhost -A m -A p

-R all|m|r|p|c|w

Removes support for one or more features. The following identifiers are used for ASP.NET features.

IdentifierAffects

allAll features

mMembership

rRole management

pProfile

cWeb Parts personalization

wWeb events

Feature identifiers can be specified together or separately, as shown in the following examples.

aspnet_regsql.exe -E -S localhost -R mp

aspnet_regsql.exe -E -S localhost -R m -R p

-Q

Runs the tool in quiet mode and does not confirm before removing a feature.

In this section , we can create our security database according to our business model and store it on sql server, oracle, mysql or other.

If you have already a security database, go to the next section.

Open visual studio prompt command tool and run command line aspnet_regsql as following

The screen explain the wizard scenario so Click next

Here we can remove existing security database or create a new one. We want to create a new security database. So check the first option and click next

Enter our database server name .\SQLEXPRESS ( enter the appropriate server name). if you already an existing database, you can select it. So the wizard will create the security tables on the selected datase.

If you do not have a database, let default. the default database name that will be created is aspnetdb

The wizard dispays the summary action, so click next to confirm and finish the action

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.

You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

Let’s talk about password encoding and decoding and take the opportunity to introduce the Unit Of Work Pattern used to insert and retrieve data.

There exists a sequence of hash functions SHA-0, SHA-1, SHA-2 and the most recent SHA-3.

SHA-3, is a new cryptographic hash function that has been selected by NIST in October 2012 following a public competition launched in 2007, this because the weaknesses discovered on MD-5 and SHA-1 let fear fragility SHA-2 is built on the same schéma. It has variations that can produce hashes 224, 256, 384 and 512 bits. It is built on a different principle from that of MD5, SHA-1 and SHA-2 functions.

So in our tutorial, we will use the SHA-3 512 bits,

For this, it is not intended to replace SHA-2, which is at present not been compromised by a significant attack, but to provide an alternative response to attacks against MD5 possibilities standards SHA-0 and SHA-1.

A. Unit Of Work Pattern

We are using the default ASP.NET Membership database, so execute the script if it does not exist in your test database server, please see our tutorial

Generate the model and classes from membeship database (Model.Context.tt, Model.Entities.tt and Model.mapping.tt ) . If you are newly in Entity Framwork, please read our tutorial Introduction to entity framework Code first

We will use the DBContextFactory interface to handle multiple database or schemas, for example if a database contains multiple schemas, we will have the opportunity to work with multiple schemas within a single context.

Lets create a IUnitOfWork interfaceand implement it

IUnitOfWork interface will be used only to get Repositories, save context and finally dispose objects

B. Implementation of MembershipProvider

Our CustomMembershipProvider derives from MembershipProvider

The first thing we are doing is to override Initialize(string name, NameValueCollection config) so as to get config parameters and also get ApplicationId or create it if does not exist

In cryptography, a salt is random data that are used as an additional input to a one-way function that hashes a password or passphrase. The primary function of salts is to defend against dictionary attacks and pre-computed rainbow table attacks.

A new salt is randomly generated for each password. In a typical setting, the salt and the password are concatenated and processed with a cryptographic hash function, and the resulting output (but not the original password) is stored with the salt in a database. Hashing allows for later authentication while defending against compromise of the plaintext password in the event that the database is somehow compromised.

Now, to << decode >> the password (if one can speak of decoding) we can simply hash the password provided by the user with the basic salt stored on database and compare the resulting hash with the hash stored in the database.

So one and only the user knows the password. If any one else can discover the password then we are the victim of a successful attack.

The validate function can look like this

Try it :

public override bool ValidateUser(string username, string password)
{
// Get the user so as to find Salt and Hashed Password
aspnet_Users user = new MemberShipService().GetUser(username, _applicationId);

if (user != null)
{
// hash the password provided by the user with the basic salt stored on database and compare
// the resulting hash with the hash stored in the database

Microsoft’s ADO.NET Entity Framework (EF) simplifies data access by allowing you to avoid working directly with the database in your code. Instead you can retrieve data by writing queries against strongly typed classes letting the Entity Framework handle the database interaction on your behalf. EF can also persist changes back to the database for you. In addition to this benefit, you will also benefit from the EF’s comprehension of relationships. This means you will not be required to write extra code to specify joins between entities when expressing queries or simply working with your objects in memory.

EF provides you with three ways to define the model of your entities. Using the database first workflow, you can begin with a legacy database to create a model. With the model first workflow, you can design a model in a designer. Or you can simply define classes and let EF work with those—referred to as code first.

In tis tutorial, we are going to introduce Entity Framework using the Database Code First approach:

Then we start from an existing database, which lets us create the model by a simple drag and drop.

Here, we are going to move our generated items to new folders or project so as to remove the model.edmx file and become independent of it)

So Create a folder CodeFirstModel and move the content of Model.Entities.tt on it

Create a folder CodeFirstMapping and move the content of Model.Mappings.tt on it

Create a folder CodeFirstContext and move the file of Model.Context.cs on it

now, we can delete our model.edmx file

Finally, we can clean our connectionString by removing all metadata

Now, we can start testing our work

B : Entity Framwork Code first Without an existing Database

In this case, we don’t have an existing database (the goals is to enable a more code-centric option which we call “code first development”).

So, lets create a class named Product (the sample is based on Nothwind Sample database)

Create a Vendor Class as follow

Create a ProductVendor class as follow. Note that a Product can have many Vendors and a vendor can sell many Products.

Our next step is to define Mapping between classes so as to define our database objects.

Note that it is possible to do Code First without mapping relationships between classes . In this case our databases objects will be created as the names of our classes and database fields as the name of our class properties.

Microsoft’s ADO.NET Entity Framework (EF) simplifies data access by allowing you to avoid working directly with the database in your code. Instead you can retrieve data by writing queries against strongly typed classes letting the Entity Framework handle the database interaction on your behalf. EF can also persist changes back to the database for you. In addition to this benefit, you will also benefit from the EF’s comprehension of relationships. This means you will not be required to write extra code to specify joins between entities when expressing queries or simply working with your objects in memory.

EF provides you with three ways to define the model of your entities. Using the database first workflow, you can begin with a legacy database to create a model. With the model first workflow, you can design a model in a designer. Or you can simply define classes and let EF work with those—referred to as code first.

In tis tutorial, we are going to introduce Entity Framework using the Database First approach.

Then we start from an existing database, which lets us create the model by a simple drag and drop.

A : Entity Framwork database first Model Creation

So, lets create a Class Library project

Add an ADO.NET Entity Data Model (.edmx file ) Item

Choose Generate from database option because will generate our model from an existing database

Here, Will connect to SQL Server or another database Server, So Microsoft SQL SERVER as Data Source, if we use another database Server click change.

Type or select our Server Name (SQLEXPRESS) in our case

Select our authentication Mode

Select ASPNETDB Database (in our case, we are going to use this database for test), If you do not have the ASPNETDB Database you can download it at the end tutorial

Check Table Objet, we no need Stored Procedures and views

Click finish to create our model. The generated model will look like

By right clicking our Model , we have possibilities to explore our database

In this tutorial we learn how to create a custom Membership provider to store and retrieve data associated with a user in SQL Server tables. So we can use the default ASPnetDB database or use a separate databse from the standard ASP.NET membership provider’s default database.

The principles covered in this tutorial will apply to creating Membership providers for other databases like Access and Oracle. After learning how to create the custom Membership provider we learn how to use the it in a asp.net web site and finally we will extend it to use external logins like facebook, google, yahoo. etc…