Working With SimpleMembership in ASP.Net MVC

Introduction

Today we'll work on the membership and role management in MVC 4. The Authentication and Authorization are the main features of the web application. The default membership is also provided in many projects and this is quite inflexible in terms of the database schema. Suppose we are using the default membership, then we do not have much more control over the table in the database. This creates complexity and difficulty in the situation where the login info of the user needs to be stored in a table with the customized schema.

We'll work here with the SimpleMembership that is introduced with the WebMatrix. Now we can create a flexible model for authenticating the new users. It is based on the basic membership and roles (SimpleRole) provider of ASP.NET but wraps them in an easy and flexible way. You can also have a look at the following structure in which the hierarchy of SimpleMembership is defined:

SimpleMembership Hierarchy

You can understand SimpleMembership better with the architecture of SimpleMembership defined above. So, let's work on the following scenario:

  • Create Database

  • Create MVC App for use SimpleMembership

  • Create Controllers

  • Create Registration Page

  • Create Login Page

Create Database

At first we need to create a database named "SampleDb" and now we'll create a table named "Users" to store the user information. You can have a look at the following table design to design the table:

Table Design

Create MVC App for Use SimpleMembership

Now in this section we'll create the ASP.NET Web Application based on the MVC 4 Project Template using the following procedure.

Step 1: Open the Visual Studio and click on "New Project".

Step 2: Select the MVC 4 application as shown below:

Creating MVC 4 Application

Step 3: Select an Empty Project and select "ASPX" View engine and click "OK".

Mvc4 Empty Application

Step 4: Now in the Solution Explorer, right-click on the References and select "Add References".

Step 5: Add the WebMatrix references as shown below:

Adding WebMatrix Reference

Step 6: Now open the Web.Config file and modify it with the highlighted code below:

  1. <system.web>  
  2.   <httpRuntime targetFramework="4.5.1" />      
  3.   <compilation debug="true" targetFramework="4.5.1" />  
  4.   <pages>  
  5.     <namespaces>  
  6.       <add namespace="System.Web.Helpers" />  
  7.       <add namespace="System.Web.Mvc" />  
  8.       <add namespace="System.Web.Mvc.Ajax" />  
  9.       <add namespace="System.Web.Mvc.Html" />  
  10.       <add namespace="System.Web.Routing" />  
  11.       <add namespace="System.Web.WebPages" />  
  12.     </namespaces>  
  13.   </pages>  
  14.   <authentication mode="Forms">  
  15.     <forms loginUrl="~/Account/Login"></forms>  
  16.   </authentication>  
  17.   <membership defaultProvider="SampleProvider">  
  18.     <providers>  
  19.       <add name="SampleProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>  
  20.     </providers>  
  21.   </membership>  
  22.   <roleManager enabled="true" defaultProvider="SampleProvider">  
  23.     <providers>  
  24.       <add name="SampleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>  
  25.     </providers>  
  26.   </roleManager>   
  27. </system.web> 

In the code above, you can see that the Forms authentication is enabled for the application and forms loginurl is set to the login. The SimpleMembershipProvider is also set in the providers and roleManager sections.

Step 7: Now you add the connection string to connect with the database as shown in the following code:

  1. <connectionStrings>  
  2.   <add name="MembershipDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SampleDb;User ID=”UserID”;Password=”password” " providerName="System.Data.SqlClient"/>  
  3. </connectionStrings> 

Create Controllers

In this section we'll create the controllers for the application. Follow the procedure below.

Step 1: In the Solution Explorer, right-click on the Controllers folder to add a new controller.

Adding New Controller in MVC

Step 2: Enter the Controller name as "Account" and click "OK".

Adding Controller

Step 3: Replace the code with the following code in the AccountController:

  1. using System.Web.Mvc;  
  2. using WebMatrix.WebData;  
  3. namespace MvcMembershipApp.Controllers  
  4. {  
  5.     public class AccountController : Controller  
  6.     {  
  7.         //  
  8.         // GET: /Account/  
  9.         public ActionResult Index()  
  10.         {  
  11.             return View();  
  12.         }  
  13.         [HttpGet]  
  14.         public ActionResult Login()  
  15.         {  
  16.             if (!WebSecurity.Initialized)  
  17.             {  
  18.                 WebSecurity.InitializeDatabaseConnection("MembershipDbContext""Users""ID""Name", autoCreateTables: true);  
  19.             }  
  20.             return View();  
  21.         }  
  22.         [HttpPost]  
  23.         public ActionResult Login(FormCollection Form)  
  24.         {  
  25.             bool Authenticated = WebSecurity.Login(Form["UserName"], Form["Password"], false);  
  26.             if (Authenticated)  
  27.             {  
  28.                 string Return_Url=Request.QueryString["ReturnUrl"];  
  29.                 if (Return_Url == null)  
  30.                 {  
  31.                     Response.Redirect("/Home/Index");  
  32.                 }  
  33.                 else  
  34.                 {  
  35.                     Response.Redirect(Return_Url);  
  36.                 }  
  37.             }  
  38.             return View();  
  39.         }  
  40.         [HttpGet]  
  41.         public ActionResult Register()  
  42.         {  
  43.             if (!WebSecurity.Initialized)  
  44.             {  
  45.                 WebSecurity.InitializeDatabaseConnection("MembershipDbContext","Users","ID","Name",autoCreateTables:true);  
  46.             }  
  47.             return View();  
  48.         }  
  49.         [HttpPost]  
  50.         public ActionResult Register(FormCollection Form)  
  51.         {  
  52.             WebSecurity.CreateUserAndAccount(Form["Name"], Form["Password"], new { UserName = Form["UserName"], City = Form["City"] });  
  53.             Response.Redirect("~/Account/Login");  
  54.             return View();  
  55.         }  
  56.         public ActionResult Logout()  
  57.         {  
  58.             WebSecurity.Logout();  
  59.             Response.Redirect("~/Account/Login");  
  60.             return View();  
  61.         }  
  62.     }  
  63. } 

In the code above both the Register and Login action methods are intended for the GET requests with no parameter and invoke the InitializeDatabaseConnection() method of the WebSecurity class. This method initializes the database connection and ensures that the tables needed by the SimpleMembership is available. The methods that are intended to POST requestes accepts the FormCollection parameter. The Register() (POST) method creates the user account using the CreateUserAndAccount() method and store the data into table. The Login() (Post) method called when the login page is submitted by the user.

Step 4: Add a new controller named HomeController and replaces the code with the following code:

  1. using System.Web.Mvc;  
  2. using WebMatrix.WebData;  
  3. namespace MvcMembershipApp.Controllers  
  4. {  
  5.     public class HomeController : Controller  
  6.     {  
  7.         //  
  8.         // GET: /Home/  
  9.         public ActionResult Index()  
  10.         {  
  11.             if (!WebSecurity.IsAuthenticated)  
  12.             {  
  13.                 Response.Redirect("~/Account/Login");  
  14.             }  
  15.             return View();  
  16.         }  
  17.     }  
  18. } 

Working With Views

Create Registration Page

Now in this section we'll create the registration page using the following procedure.

Step 1: Add a new folder named Account in the Views folder.

Adding Folder in Views

Step 2: Now add a new view on the Account folder by right-clicking and enter the name as "Register".

Adding View in MVC 4

Step 3: Replace the body code with the following code:

  1. <h1>Register</h1>  
  2. <form method="post" action="Register">  
  3.     <table cellpadding="3">  
  4.         <tr>  
  5.             <td>Name :</td>  
  6.             <td>  
  7.                 <input type="text" name="Name" /></td>  
  8.         </tr>  
  9.         <tr>  
  10.             <td>Password :</td>  
  11.             <td>  
  12.                 <input type="password" name="Password" /></td>  
  13.         </tr>  
  14.         <tr>  
  15.             <td>User Name :</td>  
  16.             <td>  
  17.                 <input type="text" name="UserName" /></td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td>City :</td>  
  21.             <td>  
  22.                 <input type="text" name="City" /></td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td colspan="2">  
  26.                 <input type="submit" value="Register"></td>  
  27.         </tr>  
  28.     </table>  
  29. </form> 

Create Login Page

Add a new view named Login and replace the body code with the following code:

  1. <h1>Login</h1>  
  2. <form method="post" action="/Account/Login">  
  3.     <table cellpadding="3">  
  4.         <tr>  
  5.             <td>User Name :</td>  
  6.             <td>  
  7.                 <input type="text" name="UserName" /></td>  
  8.         </tr>  
  9.         <tr>  
  10.             <td>Password :</td>  
  11.             <td>  
  12.                 <input type="password" name="Password" /></td>  
  13.         </tr>  
  14.         <tr>  
  15.             <td colspan="2">  
  16.                 <input type="submit" value="Login"></td>  
  17.         </tr>  
  18.         <tr>  
  19.             <td colspan="2"><a href="Register">New user?</a></td>  
  20.         </tr>  
  21.    </table>  
  22. </form> 

Create Index Page

Step 1: Add a new folder named Home in the Views folder.

Step 2: Create a new view as named Index in the Home folder and replace the code with the following code:

  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>  
  2. <%@ Import Namespace="WebMatrix.WebData" %>  
  3. <!DOCTYPE html>  
  4. <html>  
  5. <head runat="server">  
  6.     <meta name="viewport" content="width=device-width" />  
  7.     <title>Index</title>  
  8. </head>  
  9. <body>  
  10.     <div>  
  11.         <form method="post" action="/account/logout">  
  12.             <h1>Welcome <%= WebSecurity.CurrentUserName %>!</h1>  
  13.             <input type="submit" value="Logout" />  
  14.         </form>  
  15.     </div>  
  16. </body>  
  17. </html> 

Running Application

Step 1: Now run the application by pressing F5 and click on the "NewUser" Link.

Login View

Step 2: Register the user.

Registering User

When the registration process completes, it'll redirect you to the Login Page. You can see that the database has been modified after running the application.

Users Table in Database

Summary

This article describes how to use the SimpleMembership instead of the default membership and role management features of ASP.NET. You can create a custom database for the users table to store the data. Thanks for reading.


Similar Articles