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.
- 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.
- Membership providers in ASP.NET MVC.
- 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="DBConnection" connectionString="Data Source=MUNESH-PC;Database=MVCApp;UID=sa;Password=*****" providerName="System.Data.SqlClient" />
- </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.
- 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, 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:
- 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)
- {
-
- 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));
- }
- }
-
- 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.