The Wayback Machine - https://web.archive.org/web/20131125141104/http://www.codeguru.com:80/csharp/.net/net_asp/mvc/using-simplemembership-in-asp.net-mvc-4.htm

Using SimpleMembership in ASP.NET MVC 4

Features such as membership and role management have been a part of ASP.NET core infrastructure since version 2.0. Developers have been using the default membership provider and role provider in their web applications. However, a common observation is that the default membership and role providers are quite rigid in terms of database schema and the way user information is stored. Luckily, SimpleMembership provides a helping hand in this area. It extends the core membership and role providers in such a way that you can use a custom database table to store user information. This article gives you step by step instructions to configure and use the SimpleMembership in ASP.NET MVC projects.

Overview of SimpleMembership

Authentication and authorization are commonly needed features in any modern web application. ASP.NET 2.0 introduced membership and role management through the provider model. Although the default membership and role providers work well in many situations, they are quite rigid in terms of database schema and the way they store user information in the database. For example, while using the default membership provider you don't have much control on the table in which user names (login names) are stored. This rigidity creates difficulties in situations where user login information needs to be stored in a table with custom schema or in situations where authentication is happening via some third party (OAuth based authentication for example).

SimpleMembership, introduced with WebMatrix, tries to address these issues by offering a flexible model for authenticating the users. It relies on the core membership and roles provider of ASP.NET but wraps them in an easy to use and flexible way. Have a look at the following figure that shows the inheritance hierarchy of SimpleMembership.

The inheritance hierarchy of SimpleMembership

The inheritance hierarchy of SimpleMembership

WebMatrix.WebData assembly contains two important classes, viz. SimpleMembershipProvider and SimpleRoleProvider. The SimpleMembershipProvider class inherits from the ExtendedMembershipProvider class that in turn inherits from the MembershipProvider class residing in the System.Web.Security namespace. The SimpleRoleProvider class inherits directly from the RoleProvider class from the System.Web.Security namespace.

Obviously, in order to use SimpleMembership you must refer to the WebMatrix.WebData assembly in your ASP.NET MVC 4 project. If you create a new ASP.NET MVC project using the Internet Application template then by default the project template uses SimpleMembership and already refers to the WebMatrix.WebData assembly. The login system of this template is based on SimpleMembership. However, in the remainder of this article you will not use this template for a couple of reasons. Firstly, you may want to create a blank web site that doesn't include SimpleMembership by default. Secondly, you may not want to use the default login system (AccountController) provided by the Internet Application template. In the later case it is important for you to understand how SimpleMembership works before you use it in your websites.

Creating a Database

For the sake of this example you will create a new SQL Server database named UserDb that stores user information. The following figure shows the Users table from the UserDb database:

The Users table from the UserDb database

The Users table from the UserDb database

As you can see, this is a custom table. SimpleMembership expects only two simple things from the table schema:

  • It should have a column that acts as a unique user identifier (Id column in this case).
  • It should have a column that acts as a login name (UserName in this case).

The interesting thing is that you can give any name to the above two columns. For example in the above figure the column storing user identifier is named as Id but you could have named it as UserID or Uid. Also, note that the Users table contains columns not used by SimpleMembership provider - DisplayName and Country. These columns are custom application specific columns and it depends on you as to how you would like to use the information stored in them.

Configuring an MVC Application to use SimpleMembership

In order to see how SimpleMembership can be used, create a new ASP.NET MVC 4 web application using the Empty project template and ASPX view engine.

New ASP.NET MVC 4 web application using the Empty project template and ASPX view engine

New ASP.NET MVC 4 web application using the Empty project template and ASPX view engine

Then add a reference to WebMatrix.WebData assembly using the "Add Reference" menu option. Merely adding a reference to WebMatrix.WebData is not sufficient. You also need to tell ASP.NET MVC to use this provider using the web.config file. So, open the web.config file and enable Forms authentication for your web application:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" />
</authentication>

As shown above you set the authentication mode to Forms and also set the loginUrl to ~/Account/Login. You will develop the Account controller in later sections. Further add the following markup that specifies the provider information:

<membership defaultProvider="p1">
  <providers>
    <add name="p1" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
  </providers>
</membership>

<roleManager enabled="true" defaultProvider="p1">
  <providers>
    ...
  </providers>
</roleManager>

As you can see the <providers> section of the <membership> specifies the provider type as WebMatrix.WebData.SimpleMembershipProvider. Also, ensure that enabled attribute of <roleManager> is set to true to enable role management features.

Also, add a database connection string in the <connectionStrings> section that points to the UserDb database you created earlier.

<connectionStrings>
  <add name="UserDb" connectionString="data source=.\sqlexpress;
                     initial catalog=userdb;uid=<user_id_here>;pwd=<pwd_here>;
                     integrated security=sspi" providerName="System.Data.SqlClient" />
</connectionStrings>

Creating a User Registration Page

Next, add a new controller class to the project and name it as AccountController. The AccountController class contains all the action methods related to user registration, logging in and logging out. The following code shows the Register() action method that creates a new user.

[HttpGet]
public ActionResult Register()
{
    if (!WebSecurity.Initialized)
    {
        WebSecurity.InitializeDatabaseConnection("UserDb", "Users", "Id", "UserName", autoCreateTables: true);
    }
    return View();
}

[HttpPost]
public ActionResult Register(FormCollection form)
{
    WebSecurity.CreateUserAndAccount(form["username"], form["password"], new{DisplayName = form["displayname"], Country=form["country"]});
    Response.Redirect("~/account/login");
    return View();
}

The first version of the Register() action method is intended for GET requests (i.e. when user navigates to registration page) and accepts no parameter. This method invokes the InitializeDatabaseConnection() method of WebSecurity class. WebSecurity is a helper class and resides in WebMatrix.WebData namespace itself. The InitializeDatabaseConnection() method does an important task. It initializes a database and ensures that certain tables needed by SimpleMembership are available. The first parameter of the InitializeDatabaseConnection() method is the database connection string name as stored in the web.config file. The second parameter is the table name that stores user information. The third parameter is the name of the user identifier column. The fourth parameter is the name of the column that stores user names. The autoCreateTables parameter controls whether the tables needed by SimpleMembership are created automatically or not.

When the above call to the InitializeDatabaseConnection() method executes it creates the following tables in the UserDb database:

UserDb database

UserDb database

Notice all the tables that start with webpages_. They are needed by SimpleMembership to store membership and role information. Also notice that the call to InitializeDatabaseConnection() method is wrapped inside an if statement that checks whether the database is already initialized or not. This is done using the WebSecurity.Initialized property.

Now let's discuss the second version of Register() action method. The second version is intended for POST requests and hence it accepts the FormCollection parameter. The Register view submits to this version of the Register() action method. Inside you use the CreateUserAndAccount() method of the WebSecurity class. The CreateUserAndAccount() method accepts UserName, Password and other pieces of information stored in the Users table. The properties of the anonymous object must match with the column names of the Users table. After successful registration the user is taken to the login page. The following figure shows the Register view:

The Register view

The Register view

Creating a Login Page

Now that you have completed the user registration page, let's develop the login page and associated action methods. The following code shows Login() action methods from the AccountController:

[HttpGet]
public ActionResult Login()
{
    if (!WebSecurity.Initialized)
    {
        WebSecurity.InitializeDatabaseConnection("UserDb", "Users", "Id", "UserName", autoCreateTables: true);
    }
    return View();
}

[HttpPost]
public ActionResult Login(FormCollection form)
{
    bool success = WebSecurity.Login(form["username"], form["password"], false);
    if (success)
    {
        string returnUrl = Request.QueryString["ReturnUrl"];
        if (returnUrl == null)
        {
            Response.Redirect("~/home/index");
        }
        else
        {
            Response.Redirect(returnUrl);
        }
    }
    return View();
}

The first version of Login() action method is very similar to the first version of the Register() method and merely initializes the SimpleMembership. The second version of Login() action method is intended for POST requests. It gets called when the Login page is submitted by the end user. It accepts a parameter of type FormCollection. Inside, it calls the Login() method of WebSecurity by passing a user name and password. Recollect that you have enabled forms authentication for your web application and the last parameter of the Login() controls whether to create a persistent forms authentication cookie (true) or not (false). The Login() returns a boolean value indicating whether a login attempt was successful (true) or not (false). Based upon the outcome of the login process you can either take the user to another page or display some error message (not shown in the code above).

The Login view that submits to the Login() action method is shown below:

The Login view

The Login view

Individual action methods that expect a user to be authenticated can check whether a user has been successfully authenticated or not as follows:

public ActionResult Index()
{
    if (!WebSecurity.IsAuthenticated)
    {
        Response.Redirect("~/account/login");
    }
    return View();
}

The IsAuthenticated property of the WebSecurity class returns true if the current user is an authenticated user. If you wish you can also get the UserName using the CurrentUserName property of WebSecurity (not shown in the code).

Logging Out

Logging out a user is just a matter of calling the Logout() method of WebSecurity. The Logout() action method of the AccountController does just that and is shown below:

public ActionResult Logout()
{
    WebSecurity.Logout();
    Response.Redirect("~/account/login");
    return View();
}

Once a user is logged out he is taken back to the login page.

Role Management

You might be wondering how role management works under SimpleMembership. Since SimpleRoleProvider is directly based on the System.Web.Security.RoleProvider class, you can use the same core methods for role management. For example, you can use the Roles.CreateRole() method to create roles, Roles.GetAllRoles() to get a list of all the roles and so on. Though not discussed in this article, the WebSecurity class also adds a few easy to use methods that deal with authorization.

Summary

SimpleMembership provides a nice alternative to the default membership and role management features of ASP.NET. Built on the top of the core ASP.NET membership it allows you to have a custom database schema for the users table. The WebMatrix.WebData namespace includes SimpleMembershipProvider and SimpleRoleProvider classes that can be used as membership provider and role provider in an ASP.NET MVC application. The WebSecurity helper class is an easy to use wrapper that allows you to quickly authenticate a user.



Related Articles

Downloads

Comments

  • the Claim

    Posted by Kirill on 07/03/2013 01:59am

    Don't you think that it is a little bit silly when you post quick start guide for beginners like this with something like that: ... Why don't you post required string instead of dots?

    Reply
  • Independent study presents you with 2 fresh new stuff about nike that not a soul is covering.

    Posted by BobHotgloff on 05/23/2013 12:24am

    Concepts behind sneakers that you are able take full advantage of starting today. [url=http://www.shoesjp.biz/new-balance【ニューバランス】-c-670.html]new balance[/url] Precisely why every little thing you might have discovered about sneakers is actually drastically wrong and what you should learn. [url=http://www.shoesjp.biz/nike【ナイキ】-c-634.html]ナイキ スニーカー[/url] Brief article helps you with all the ins and outs on shoes combined with everything you ought to do today. [url=http://www.kutujp.biz/]アディダス[/url] Hot shoes Guide Shares The Way To Dominate The shoes Arena [url=http://www.kutujp.biz/アディダス-adidas-c-4.html]アディダス シューズ[/url] As to the reasons all things you might have find out about shoes is actually drastically wrong and what you should realize. [url=http://www.kutujp.biz/アシックス-asics-c-3.html]アシックス[/url] The very best approach for shoes that you can learn right now. [url=http://www.kutujp.biz/ナイキ-nike-c-13.html]ナイキスニーカー[/url] Unique article tells the low down upon sneakers and as well as the reasons you have to take action straight away. [url=http://www.kutujapan.org/]アディダス[/url] All new sneakers Ebook Tells The Right Way To Rule The shoes Arena [url=http://www.kutujapan.org/adidas-アディダス-c-74.html]adidas originals[/url] Upcoming sneakers Book Unveils Techniques To Rule The sneakers Arena [url=http://www.kutujapan.org/new-balance-ニューバランス-c-13.html]ニューバランス 574[/url] What professionals normally are not saying about shoes and how this is affecting you. [url=http://www.kutujapan.org/nike-ナイキ-c-78.html]ナイキ[/url] Reasons to people are dead wrong regarding sneakers and the reason why you will have to look at this study. Challenging Tips On How To Gain knowledge shoes And Also The Way One Can Be part of The sneakers Top dogs [url=http://www.shoesja.biz/]アシックス[/url] Accessories and creation in Austin -- shoes has left without goodbye [url=http://www.shoesja.biz/adidas-アディダス-c-64.html]アディダス[/url] Their shoes Corporation Presentation : Persons who cares about nothing is successful?? [url=http://www.shoesja.biz/new-balance-ニューバランス-c-21.html]newbalance[/url] Interesting queries about shoes have been answered and in addition the reasons you will want to view each concept in this write up. [url=http://www.shoesja.biz/nike-ナイキ-c-44.html]ナイキ スニーカー[/url] Information about how to understand all sorts of things there is to know regarding shoes in nine basic steps. [url=http://www.kutuja.com/]ベルーナ[/url] The right way to comprehend all the details there is to learn about shoes in Few simple and easy steps. [url=http://www.kutuja.com/adidas【アディダス】-c-1.html]adidas[/url] Contemporary questions about sneakers clarified and the reasons you would need to go through every single statement in this documentation. [url=http://www.kutuja.com/new-balance【ニューバランス】-c-206.html]newbalance[/url] Ideal magic formula for shoes that you could discover as we speak. [url=http://www.kutuja.com/nike【ナイキ】-c-215.html]nike[/url] An actual double take on shoes [url=http://www.shoesjp.biz/]アシックス[/url] The Magic Ingredients For shoes [url=http://www.shoesjp.biz/adidas【アディダス】-c-640.html]adidas originals[/url] A suitable double sprain on shoes

    Reply
  • I've got an error message.

    Posted by picharnan on 05/20/2013 03:45am

    Can you help me to fix this, I've got an error message that Keyword not supported: 'provider'. Thank for future. :)

    Reply
  • Questions

    Posted by Nico on 05/02/2013 12:58pm

    Hi thanks for this article. It s good to see how to use it in normal project. I have two questions. How to use rôle? How does Internet template use simplemembership by default behind the scenes? Cheers from Paris

    Reply
  • Crucial Key Elements To help you rule the nike-world Is Pretty Simple!

    Posted by Acuddence on 04/30/2013 10:13am

    Contemporary questions regarding nike resolved and therefore the reasons why you should read in detail each and every concept in this report.[url=http://www.nikejpgolf.biz/]ゴルフ ナイキ[/url] An explicit double twist on nike [url=http://www.nikejpgolf.biz/nike-ゴルフボール-c-23.html]nikegolf[/url] Recent queries about nike replied and in addition the reasons you should definitely read through every word on this guide. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ナイキゴルフ[/url] Unbiased site unveil A couple of fresh new stuff for nike that absolutely no one is speaking about. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ナイキゴルフ[/url] Generally nike Industry Chat - Employees who likes virtually nothing is declared as the victorious one?! [url=http://www.nikejpgolf.biz/nike-ゴルフシューズ-c-15.html]ナイキ nike[/url] Products and show in Nevada : nike has left with no good bye [url=http://www.nikeyasuyi.com/]ナイキ スニーカー[/url] Products and formation throughout California - - mizuno has left without any thanks [url=http://www.nikeyasuyi.com/nikeナイキRunning-c-3.html]nike ランニング[/url] This nike Endeavor Speak -- Who loves fears is announced the victorious one?? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]nike シューズ[/url] Generally nike Company Dialog - Workers who cares about zero benefits?!? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]ナイシューズ[/url] nike adds spanking new life span for an old challenge-- metallic set

    Reply
  • small question about Web.config

    Posted by Dmitry on 04/19/2013 10:17pm

    Hi, Bipin, thanks for the article. When I added the following markup to the file web.config: and then launch the project, there was such an error: "Could not load file or assembly "WebMatrix.WebData" or one of its dependencies. Can not find the file specified." I don't forgot to add a reference to WebMatrix.WebData assembly in my project. Why this error occurs? Thank you.

    Reply

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds