ASP.NET MVC Membership Provider

Here we will learn how to use membership provider in ASP.NET MVC, and how to create users, and their roles using ASP.NET MVC membership, and with this we will also learn how to assign roles to users in ASP.NET MVC membership provider, and how to remove users from roles, after getting all roles of users from ASP.NET MVC membership and we will implement security in ASP.NET MVC applications with examples.

To make security in ASP.NET MVC application use the following method to create the security in ASP.NET MVC application.

  1. Authentication And Authorization in ASP.NET MVC.

    Authentication: It is the process of checking that the user is valid or not.
    Authorization: It is the process of checking that the user is applicable for the process or not.

  2. Membership providers in ASP.NET MVC.

  3. Roles based authentication for user in ASP.NET MVC.

We will learn how to create a database for the membership provider in ASP.NET MVC and how to assign role to user, we will create a registration page to understand this.

Let’s create a application for membership provider ASP.NET MVC.

Step 1: Go to visual studio and click on new project -> a window will open from here select a 'ASP.NET MVC4 web application' and give the name for this project in my case I give it as “MVCMembershipProvider ".

Now click ok and select a template as Internet Application and engine as Razor engine , after sleeting all these click ok. it will click a solution project this will contain .css file ,script file and MVC application structure.

Step 2: After creation of application let's create a database for this and give the name for this database i gave it as 'MVCApp' and then add a connection string to the database.

  1. <connectionStrings>  
  2.     <add name="DBConnection" connectionString="Data Source=MUNESH-PC;Database=MVCApp;UID=sa;Password=*****" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
After adding the connection string to the project now we need to create membership tables to the database but before this go to the models folder and have a look on AccountModels.cs class. this class automatically create when we select mvc application as Internet application.

AccountModel.cs class contain following methods.

Now for creating membership tables in database initialize the connection in globel.asax . here we will use code first approach for that we need to add following code in this class.

For adding data table in database membership we need to add a line of code in Global.asax.
  1. WebSecurity.InitializeDatabaseConnection("DBConnection""UserProfile""UserId","UserName", autoCreateTables: true);  
Here namespace for WebSecurity is “using WebMatrix.WebData;


Definition for the InitializeDatabaseConnection is:
  1. Public static void InitializeDatabaseConnection (string connectionStringName, stringuserTableName, string userIdColumn, string userNameColumn, bool autoCreateTables);  


  • connectionStringName: It the name of database table where user information stored.

  • userTableName: It contain user profile information.

  • userIdColumn: This column name of table contain user ID this should be integer.

  • userNameColumn: Column name of table contain user name. This column is basically used to match profile data of user with membership account data.

  • autoCreateTables: True to indicate that user profile and membership tables should be created if they do not exist; false to indicate that tables should not be created automatically. Although the membership tables can be created automatically, the database itself must already exist.

Now globel.asax page will look like:

Now after all this configuration let's run your application and see the ur hoe page and click on register link which is your page's right side.

After running your application you go to the database and see the table, it will generate the following tables for us

When you will click on registration link the following screen will open with 3 fields.

We can add more fields to this view, for making changes in registration view 1st weneed to add field in database and the  table name is “UserProfile”;

Here we added 3 columns as shown above; now we need to add these column parameters in registration model, it is in Account.cs class which is available in Model.

Code for registration model is:

  1. public class RegisterModel  
  2. {  
  3.     [Required]  
  4.     [Display(Name = "User name")]  
  5.     public string UserName  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     [Required]  
  11.     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  12.     [DataType(DataType.Password)]  
  13.     [Display(Name = "Password")]  
  14.     public string Password  
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     [DataType(DataType.Password)]  
  20.     [Display(Name = "Confirm password")]  
  21.     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]  
  22.     public string ConfirmPassword  
  23.     {  
  24.         get;  
  25.         set;  
  26.     }  
  27.     [Required]  
  28.     [Display(Name = "EmailID")]  
  29.     public string EmailId  
  30.     {  
  31.         get;  
  32.         set;  
  33.     }  
  34.     [Required]  
  35.     [Display(Name = "address")]  
  36.     public string Address  
  37.     {  
  38.         get;  
  39.         set;  
  40.     }  
  41.     [Required]  
  42.     [Display(Name = "Mobile No")]  
  43.     public string MobileNo  
  44.     {  
  45.         get;  
  46.         set;  
  47.     }  
  48. }  
Add these field in registration view:
  1. <fieldset>  
  2.     <legend>Registration Form</legend>  
  3.     <ol>  
  4.         <li>  
  5.             @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)  
  6.         </li>  
  7.         <li>  
  8.             @Html.LabelFor(m => m.Password) @Html. PasswordFor (m => m.Password)  
  9.         </li>  
  10.         <li>  
  11.             @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)  
  12.         </li>  
  13.         <li>  
  14.             @Html.LabelFor(m => m.EmailId) @Html.TextBoxFor(m => m.EmailId)  
  15.         </li>  
  16.         <li>  
  17.             @Html.LabelFor(m => m.Address) @Html.TextBoxFor(m => m.Address)  
  18.         </li>  
  19.         <li>  
  20.             @Html.LabelFor(m => m.MobileNo) @Html.TextBoxFor(m => m.MobileNo)  
  21.         </li>  
  22.     </ol>  
  23.     <input type="submit" value="Register" />  
  24. </fieldset>  
Now if you will run your application and you will see registration page it will look with new fields.

Now according to this we need to add or handle these field in controller also so for that go to Account Controller and we have to make changes in HTTPPost method of registration Action.

Now the code for this action according to old registration model is:
  1. WebSecurity.CreateUserAndAccount(model.UserName, model.Password);  
Now will make changes in this according to new model:
  1. WebSecurity.CreateUserAndAccount(model.UserName, model.Password,  
  2. new  
  3. {  
  4.    EmailID = model.EmailId,  
  5.    Address = model.Address,  
  6.    MobileNo = model.MobileNo  
  7. }  
  8. );  
So the code for the Registration action method is:
  1. [HttpPost]  
  2. [AllowAnonymous]  
  3. [ValidateAntiForgeryToken]  
  4. public ActionResult Register(RegisterModel model)  
  5. {  
  6.     if (ModelState.IsValid)  
  7.     {  
  8.         // Attempt to register the user  
  9.         try  
  10.         {  
  11.             WebSecurity.CreateUserAndAccount(model.UserName, model.Password,  
  12.                 new  
  13.                 {  
  14.                     EmailID = model.EmailId,  
  15.                         Address = model.Address,  
  16.                         MobileNo = model.MobileNo  
  17.                 }  
  18.             );  
  19.             WebSecurity.Login(model.UserName, model.Password);  
  20.             return RedirectToAction("Index""Home");  
  21.         }  
  22.         catch (MembershipCreateUserException e)  
  23.         {  
  24.             ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));  
  25.         }  
  26.     }  
  27.     // If we got this far, something failed, redisplay form  
  28.     return View(model);  
  29. }  
Now run your application and go to registration page and enter some data to fields then save it ,data will save in database.