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, with this we will also learn how to assign roles to users in asp.net mvc membership provider, and how remove users from roles, after getting all roles users from asp.net mvc membership and we will implement security in asp.net mvc applications with examples.
To making 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.
         <connectionStrings>
   <add name="DefaultConnection" connectionString = "Data Source=MUNESH-PC;Database=MVCApp;UID=sa;Password=*****" providerName="System.Data.SqlClient" />
  </connectionStrings>


if you are creating new connection string then existinf connection string in ewb config file we have remove with we have remove a following line of code from the "InitializeSimpleMembershipAttribute.cs" which available in filter folder. because it give double connection existing run time error.
                       // WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

         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
WebSecurity.InitializeDatabaseConnection("DBConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

Here namespace for WebSecurity is “using WebMatrix.WebData;

WebSecurity.InitializeDatabaseConnection
Definition for the InitializeDatabaseConnection is
public static void InitializeDatabaseConnection (string connectionStringName, string userTableName, 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 lets run your application and see the ur hoe page and click on register link which is your page right side.
After running your application you go to database and see the table, it will generate following tables for us

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

 we can add more field to this view, for making change in registration view 1st need to add field in database table name is “UserProfile”;

Here we added 3 column 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
    public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name = "EmailID")]
        public string EmailId { get; set; }

        [Required]
        [Display(Name = "address")]
        public string Address { get; set; }

        [Required]
        [Display(Name = "Mobile No")]
        public string MobileNo { get; set; }
    }




Add these field in registration view
    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html. PasswordFor (m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
            <li>
                @Html.LabelFor(m => m.EmailId)
                @Html.TextBoxFor(m => m.EmailId)
            </li>
            <li>
                @Html.LabelFor(m => m.Address)
                @Html.TextBoxFor(m => m.Address)
            </li>
            <li>
                @Html.LabelFor(m => m.MobileNo)
                @Html.TextBoxFor(m => m.MobileNo)
            </li>
        </ol>
        <input type="submit" value="Register" />
    </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
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

Now will make changes in this according to new model
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                        {
                            EmailID = model.EmailId,
                            Address = model.Address,
                            MobileNo = model.MobileNo
                        }
                        );
So the code for the Registration action method is
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                        {
                            EmailID = model.EmailId,
                            Address = model.Address,
                            MobileNo = model.MobileNo
                        }
                        );
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


Now run your application and go to registration page and enter some data to fields then save it ,data will save in database.  
                




Download this project from this link Downlaod

Share this

Related Posts

Previous
Next Post »