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:

<system.web>

    

  <httpRuntime targetFramework="4.5.1" />    

  <compilation debug="true" targetFramework="4.5.1" />

 

  <pages>

    <namespaces>

      <add namespace="System.Web.Helpers" />

      <add namespace="System.Web.Mvc" />

      <add namespace="System.Web.Mvc.Ajax" />

      <add namespace="System.Web.Mvc.Html" />

      <add namespace="System.Web.Routing" />

      <add namespace="System.Web.WebPages" />

    </namespaces>

  </pages>

 

  <authentication mode="Forms">

    <forms loginUrl="~/Account/Login"></forms>

  </authentication>

 

  <membership defaultProvider="SampleProvider">

    <providers>

      <add name="SampleProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>

    </providers>

  </membership>

 

  <roleManager enabled="true" defaultProvider="SampleProvider">

    <providers>

      <add name="SampleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>

    </providers>

  </roleManager

</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:

<connectionStrings>

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

</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:

using System.Web.Mvc;

using WebMatrix.WebData;

 

namespace MvcMembershipApp.Controllers

{

    public class AccountController : Controller

    {

        //

        // GET: /Account/

 

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpGet]

        public ActionResult Login()

        {

            if (!WebSecurity.Initialized)

            {

                WebSecurity.InitializeDatabaseConnection("MembershipDbContext""Users""ID""Name", autoCreateTables: true);

            }

 

            return View();

        }

 

        [HttpPost]

        public ActionResult Login(FormCollection Form)

        {

            bool Authenticated = WebSecurity.Login(Form["UserName"], Form["Password"], false);

 

            if (Authenticated)

            {

                string Return_Url=Request.QueryString["ReturnUrl"];

                if (Return_Url == null)

                {

                    Response.Redirect("/Home/Index");

                }

                else

                {

                    Response.Redirect(Return_Url);

                }

            }

            return View();

        }

 

        [HttpGet]

        public ActionResult Register()

        {

            if (!WebSecurity.Initialized)

            {

                WebSecurity.InitializeDatabaseConnection("MembershipDbContext","Users","ID","Name",autoCreateTables:true);

            }

 

            return View();

        }

 

        [HttpPost]

        public ActionResult Register(FormCollection Form)

        {

            WebSecurity.CreateUserAndAccount(Form["Name"], Form["Password"], new { UserName = Form["UserName"], City = Form["City"] });

            Response.Redirect("~/Account/Login");

            return View();

        }

 

        public ActionResult Logout()

        {

            WebSecurity.Logout();

            Response.Redirect("~/Account/Login");

            return View();

        }

    }

}

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:

using System.Web.Mvc;

using WebMatrix.WebData;

 

namespace MvcMembershipApp.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        public ActionResult Index()

        {

            if (!WebSecurity.IsAuthenticated)

            {

                Response.Redirect("~/Account/Login");

            }

            return View();

        }

 

    }

}

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:

<h1>Register</h1>

    <form method="post" action="Register">

        <table cellpadding="3">

            <tr>

                <td>Name :</td>

                <td>

                    <input type="text" name="Name" /></td>

            </tr>

            <tr>

                <td>Password :</td>

                <td>

                    <input type="password" name="Password" /></td>

            </tr>

            <tr>

                <td>User Name :</td>

                <td>

                    <input type="text" name="UserName" /></td>

            </tr>

            <tr>

                <td>City :</td>

                <td>

                    <input type="text" name="City" /></td>

            </tr>

            <tr>

                <td colspan="2">

                    <input type="submit" value="Register"></td>

            </tr>

        </table>

    </form>

Create Login Page

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

<h1>Login</h1>

    <form method="post" action="/Account/Login">

        <table cellpadding="3">

            <tr>

                <td>User Name :</td>

                <td>

                    <input type="text" name="UserName" /></td>

            </tr>

            <tr>

                <td>Password :</td>

                <td>

                    <input type="password" name="Password" /></td>

            </tr>

            <tr>

                <td colspan="2">

                    <input type="submit" value="Login"></td>

            </tr>

            <tr>

                <td colspan="2"><a href="Register">New user?</a></td>

            </tr>

       </table>

    </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:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<%@ Import Namespace="WebMatrix.WebData" %>

 

<!DOCTYPE html>

 

<html>

<head runat="server">

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

        <form method="post" action="/account/logout">

            <h1>Welcome <%= WebSecurity.CurrentUserName %>!</h1>

            <input type="submit" value="Logout" />

        </form>

    </div>

</body>

</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.

Up Next
    Ebook Download
    View all
    Learn
    View all