.NET MVC 4 SimpleMembership

        There are number of ways to provide authentication support for your web site. You can create your own, reuse some existing third party solution or you can use ASP .NET authentication model. Using ASP .Net authentication model is simple and it supports a number of models such as form, windows, passport etc.

ASP .NET authentication model

       The ASP.NET Membership system was introduced with ASP.NET 2.0 back in 2005. It was designed to solve common site membership requirements at the time, which generally involved username / password based registration and profile storage in SQL Server.

IMG_04032013_110215

Image 1.0 inheritance chain of SQL Membership Provider

On image 1.0 we can see inheritance chain for SqlMembershipProvider class that is used for form authentication. As you can see, the base class for all the providers is ProviderBase. The ProviderBase class resides in System.Configuration.Provider namespace from System.Configuration namespace. This class is marked as abstract and it provides template for further inheritance chain. One of the important method of this class is Initialize(). This method is used to read the configuration information of the provider from web.config file and initialize the provider. The MembershipProvider class resides in System.Web.Security namespace. This class is inherited from the ProviderBase class and adds membership specific members (especially user creation and management related members) to itself. This class is also marked as abstract. Finally, SqlMembership class from System.Web.Security inherits the MembershipProvider class. This is a concrete class that implements properties and methods from ProviderBase and MembershipProvider specifically for SQL Server databases. Similar class hierarchy can be seen for other providers such as SQL Role Provider and SQL Profile Provider.

To use SqlMembershipProvider we will need to do several steps.

  1. First, we will need to create database tables to support membership model. This can be easily done using aspnet_regsql.exe. 1

  2. Then, in web.conig under section <connectionStrings> add connectionString for membership database created in first step (image 1.2) .
  3. Finally, we need to enable SqlMembershipProvider in the <system.web><membership> section of web.config (image 1.3).

aspnet

Image 1.1 aspnet database diagram

connectionString

Image 1.2 Membership database connection string web.config setup

webconfig

Image 1.3 SQL Membership Provider web.config setup

        As simple as that, SqlMembership model is ready for use. Aldo is simple and easy to use, there were some problems in pas with this ASP .NET authentication model. The biggest problem was extending user information stored in database. Using aspnet_regsql.exe will create predefine tables for storing user information. Sometimes that is all that you need, but sometimes you want to store some extra information about user (street number, bank account etc.). In that case you have several solutions, neither of them isn’t “clean” and “nice”. You can create CustomUserDetails table and add referential integrity to aspnet_Users table created with aspnet_regsql.exe . Then store all additional information in UserDetails table. Or you can store all extra data as string in one column of aspnet_Profile table. Afcourse, there is some other solutions but they all have same problem. You are not in position to change aspnet_Users table so you must add some extra table or use profile table. This will add more complicity to your data access layer and that’s mean more job for you. Another big problem is that SqlMembershipProvider doesn’t fit well with some modern usage patterns as OAuth and OpenID.

Fortunately, ASP .NET MVC 4 brings use new membership provider, SimpleMembershipProvider that solves this problems.

ASP .NET SimpleMembershipProvider

        SimpleMembershipProvider is designed in order to solve problem with aspnet_Users table and to support new authentication patterns (OAuth and OpenID). It’s an implementation of an ExtendedMembershipProvider, which inherits from MembershipProvider and adds some other account / OAuth related things. The important thing to take away here is that a SimpleMembershipProvider is a MembershipProvider, but a MembershipProvider is not a SimpleMembershipProvider. Because of this, you can’t use existing MembershipProvider with ASP .NET MVC 4 AccountController. You will need to use old AccountController or to use SimpleMembershipProvider with new AccountControler that comes with InternetApplication template in MVC 4.

    On simple example I will show you how to create custom User table and integrate with SimpleMemebrshipProvider.

  First you will need to instal MVC 4 in your visual studio (http://www.asp.net/mvc/mvc4). Then open Visaul Stdio and create new ASP .NET MVC 4 Web Application project. As you can see on image 1.4 there is several templates for this project:

  • Empty – Really empty, just the assemblies, folder structure and a tiny bit of basic configuration.
  • Basic – Like Empty, but with a bit of UI preconfigured (css / images / bundling).

  • Internet – This has both a Home and Account controller and associated views. The Account Controller supports registration and login via either local accounts and via OAuth / OpenID providers.

  • Intranet – Like the Internet template, but it’s preconfigured for Windows Authentication.

  • Mobile – This is preconfigured using jQuery Mobile and is intended for mobile-only sites.

  • Web API – This is preconfigured for a service backend built on ASP.NET Web API.

7890879518_675c450ffc

Image 1.4 ASP .NET MVC 4 Web Application project templates

        For this example we gonna use Internet template, so select Internet template and click OK. There are lot of things that are build in Internet template, but we wont discus them in this article. Most important things for as are :

  • \Models\AccountModels.cs defines a basic user account and includes data annotations to define keys and such

  • Filters\InitializeSimpleMembershipAttribute.cs creates the membership database using the above model, then calls

  • \Controllers\AccountController.cs makes heavy use of OAuthWebSecurity (for OAuth account registration / login / management) and WebSecurity. WebSecurity provides account management services for ASP.NET MVC (and Web Pages)

  • Entity framework already added with NuGet, you can see that in packages.config file in root of your application.

Next step is to create our custom User table. Create new database and execute :

CREATE TABLE [UserProfile](

[UserId] [int] IDENTITY(1,1)NOTNULL,

[Email] [varchar](255)NOTNULL,

[FirstName] [varchar](50)NULL,

[City] [varchar](50)NULL,

CONSTRAINT [UD_User_pk] PRIMARYKEY ([UserId])

)

As you can see, this is just regular table wit some custom columns.

Final step is to connect this database with SimpleMemebrshipProvider. To do that go to web.config and change DefaultConnection connection string under <connectionStrings> collection. By default, connection is setup to store data in App_Data folder of your project. You should change it to point on your new database, like on image 1.5.

connectionString2

Image 1.5 SimpleMembership database connection string web.config setup

    Final step is to go to Filters\InitializeSimpleMembershipAttribute.cs and change this line of code :

WebSecurity.InitializeDatabaseConnection(“DefaultConnection”, “UserProfile”, “UserId”, “UserName”, autoCreateTables: true);

This is the place where SimpleMembershipProvider meets your custom User table. InitializeDatabaseConnection receives as first parameter name of connection string that points on our databse with custom User table. Second parameter is name of custom User table. Third parameter is name of primary key in custom User table. Then we have user name, in our case we will change that to Email so it will mach our table. AutoCreateTables is set to true. This means that first time when you run application, all other tables needed for simplememebrshipprovider will be created automaticly. No our InitializeDatabaseConnection will look like this :

 WebSecurity.InitializeDatabaseConnection(“DefaultConnection”, “UserProfile”, “UserId”, “Email”, autoCreateTables: true);

After we start our application, database diagram will look like on image 1.6 :

aspnet2

Image 1.6 SimpleMembership database diagram

As you can see, new tables are created and connected with custom user table. Also table for OAuth / OpenID is addded. Now you can use AccountControler to add new users and to authentication them.