ASP.NET MVC 5 Security And Creating User Role

 
A few members asked me to write an article on ASP.NET MVC security and so I planned to create a series of articles. In this series we will see:

In this article we will see how to use ASP.NET Identity in MVC Application for creating user roles and displaying the menu depending on user roles.

Here we will see how to:

  • Create default admin role and other roles.
  • Create default admin users.
  • Add Username for new User Registration.
  • Select User Role during User Registration.
  • Change Login Email with User Name.
  • Display Role Creation Menu only for Admin User.
  • Display message for normal user.
  • Redirect Unauthenticated users to default home page. 
Authentication and Authorization

Authentication

Check for the Valid User. Here the question is how to check whether a user is valid or not. When a user comes to a website for the first time he will register for that website. All his information, like user name, password, email, and so on will be stored in the website database. When a user enters his userID and password, the information will be checked with the database. If the user has entered the same userID and Password as in the database then he or she is a valid user and will be redirected to the website home page. If the user enters a UserID and/or Password that does not match the database then the login page will give a message, something like “Enter valid Name or Password”. The entire process of checking whether the user is valid or not for accessing the website is called Authentication.

 
 
Authorization

Once the user is authenticated he needs to be redirected to the appropriate page by his role. For example, when an Admin is logged in, then he is to be redirected to the Admin Page. If an Accountant is logged in, then he is to be redirected to his Accounts page. If an End User is logged in, then he is to be redirected to his page.

  

Prerequisites

Visual Studio 2015: You can download it from here.

Using the code

Create your Web Application in Visual Studio 2015

After installing our Visual Studio 2015 click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.

 
 
Select MVC and click OK.
 
 
 
Create a Database

Firstly, we will create a Database and set the connection string in web.config file for DefaultConnection with our new database connection. We will be using this database for ASP.NET Identity table creation and also our sample attendance Web project. Instead of using two databases as one for default ASP.NET user database and another for our Attendance DB, here we will be using one common database for both user details and for our sample web project demo.

Create Database: Run the following and create database script to create our sample test database. 
  1. -- =============================================                                
  2. -- Author      : Shanu                                  
  3. -- Create date : 2016-01-17                               
  4. -- Description : To Create Database                          
  5.                              
  6. -- =============================================  
  7. --Script to create DB,Table and sample Insert data  
  8. USE MASTER;  
  9. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
  10. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'AttendanceDB' )  
  11. BEGIN  
  12. ALTER DATABASE AttendanceDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE  
  13. DROP DATABASE AttendanceDB ;  
  14. END  
  15.   
  16.   
  17. CREATE DATABASE AttendanceDB  
  18. GO  
  19.   
  20. USE AttendanceDB  
  21. GO  
Web.Config

In web.config file we can find the
DefaultConnection Connection string. By default ASP.NET MVC will use this connection string to create all ASP.NET Identity related tables like AspNetUsers, etc. For our application we also need to use database for other page activities instead of using two different databases, one for User details and one for our own functionality. Here I will be using one database where all ASP.NET Identity tables will be created and also we can create our own tables for other page uses.
 
Here in connection string change your SQL Server Name, UID and PWD to create and store all user details in one database. 
  1. <connectionStrings>  
  2.     <add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog=AttendanceDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient"  />   
  3.  </connectionStrings>  
Create default Role and Admin User

Firstly, create default user role like “Admin”,”Manager”, etc and also we will create a default admin user. We will be creating all default roles and user in “Startup.cs”

  
OWIN (OPEN WEB Interface for .NET) defines a standard interface between .NET and WEB Server and each OWIN application has a Startup Class where we can specify components.

Reference

In “Startup.cs” file we can find the Configuration method. From this method we will be calling our createRolesandUsers() method to create a default user role and user. We will check for Roles already created or not. If Roles, like Admin, is not created, then we will create a new Role as “Admin” and we will create a default user and set the user role as Admin. We will be using this user as super user where the user can create new roles from our MVC application. 

  1. public void Configuration(IAppBuilder app)    
  2. {    
  3.     ConfigureAuth(app);    
  4.     createRolesandUsers();    
  5. }    
  6.   
  7.   
  8. // In this method we will create default User roles and Admin user for login    
  9. private void createRolesandUsers()    
  10. {    
  11.     ApplicationDbContext context = new ApplicationDbContext();    
  12.   
  13.     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));    
  14.     var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));    
  15.   
  16.   
  17.     // In Startup iam creating first Admin Role and creating a default Admin User     
  18.     if (!roleManager.RoleExists("Admin"))    
  19.     {    
  20.   
  21.         // first we create Admin rool    
  22.         var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();    
  23.         role.Name = "Admin";    
  24.         roleManager.Create(role);    
  25.   
  26.         //Here we create a Admin super user who will maintain the website                   
  27.   
  28.         var user = new ApplicationUser();    
  29.         user.UserName = "shanu";    
  30.         user.Email = "syedshanumcain@gmail.com";    
  31.   
  32.         string userPWD = "A@Z200711";    
  33.   
  34.         var chkUser = UserManager.Create(user, userPWD);    
  35.   
  36.         //Add default User to Role Admin    
  37.         if (chkUser.Succeeded)    
  38.         {    
  39.             var result1 = UserManager.AddToRole(user.Id, "Admin");    
  40.   
  41.         }    
  42.     }    
  43.   
  44.     // creating Creating Manager role     
  45.     if (!roleManager.RoleExists("Manager"))    
  46.     {    
  47.         var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();    
  48.         role.Name = "Manager";    
  49.         roleManager.Create(role);    
  50.   
  51.     }    
  52.   
  53.     // creating Creating Employee role     
  54.     if (!roleManager.RoleExists("Employee"))    
  55.     {    
  56.         var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();    
  57.         role.Name = "Employee";    
  58.         roleManager.Create(role);    
  59.   
  60.     }    
  61. }  

When we run our application we can see new default ASP.NET user related tables will be created in our AttendanceDB Database. Here we can see in the following image as all ASP.NET user related tables will be automatically created when we run our application and also all our default user roles will be inserted in AspNetRoles table and default admin user will be created in AspNetUsers table.

 
query result
 
Customize User Registration with adding username and Role
 
  
By default for user registration in ASP.NET MVC 5 we can use email and passoword. Here, we will customize the default user registration with adding a username and a ComboBox to display the user roles. User can enter their username and select there user role during registration.

View Part: Firstly, add a TextBox for username and ComboBox for displaying User Role in Register.cshtml,

 
 
Double click the Register.cshtml and change the html code like the following to add textbox and combobox with caption. Here we can see first we add a textbox and Combobox .We bind the combobox with (SelectList) ViewBag.Name. 
  1. @model shanuMVCUserRoles.Models.RegisterViewModel  
  2. @{  
  3.     ViewBag.Title = "Register";  
  4. }  
  5.   
  6. <h2>@ViewBag.Title.</h2>  
  7.   
  8. @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal"role = "form" }))  
  9. {  
  10.     @Html.AntiForgeryToken()  
  11.     <h4>Create a new account.</h4>  
  12.     <hr />  
  13.     @Html.ValidationSummary("", new { @class = "text-danger" })  
  14.     <div class="form-group">  
  15.         @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })  
  16.         <div class="col-md-10">  
  17.             @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })  
  18.         </div>  
  19.     </div>  
  20.   
  21.   
  22.     <div class="form-group">  
  23.         @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })  
  24.         <div class="col-md-10">  
  25.             @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })  
  26.         </div>  
  27.     </div>  
  28.     <div class="form-group">  
  29.         @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })  
  30.         <div class="col-md-10">  
  31.             @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  32.         </div>  
  33.     </div>  
  34.     <div class="form-group">  
  35.         @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })  
  36.         <div class="col-md-10">  
  37.             @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })  
  38.         </div>  
  39.     </div>  
  40.   
  41.     <div class="form-group">  
  42.         @Html.Label("user Role", new { @class = "col-md-2 control-label" })  
  43.         <div class="col-md-10">  
  44.             @*@Html.DropDownList("Name")*@  
  45.             @Html.DropDownList("UserRoles", (SelectList)ViewBag.Name, " ")  
  46.         </div>  
  47.     </div>  
  48.   
  49.     <div class="form-group">  
  50.         <div class="col-md-offset-2 col-md-10">  
  51.             <input type="submit" class="btn btn-default" value="Register" />  
  52.         </div>  
  53.     </div>  
  54. }  
  55.   
  56. @section Scripts {  
  57.     @Scripts.Render("~/bundles/jqueryval")  
  58. }  

Model Part

Next in AccountViewModel.cs check for the RegisterViewModel and add the UserRoles and UserName properties with required for validation.

model
 
Double click theAccountViewModel.cs file from Models folder, find the RegisterViewModel class, add UserName and UserRoles properties as in the following. 
  1. public class RegisterViewModel    
  2. {    
  3.     [Required]    
  4.     [Display(Name = "UserRoles")]    
  5.     public string UserRoles { getset; }    
  6.   
  7.     [Required]    
  8.     [EmailAddress]    
  9.     [Display(Name = "Email")]    
  10.     public string Email { getset; }    
  11.   
  12.     [Required]    
  13.     [Display(Name = "UserName")]    
  14.     public string UserName { getset; }    
  15.   
  16.     [Required]    
  17.     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]    
  18.     [DataType(DataType.Password)]    
  19.     [Display(Name = "Password")]    
  20.     public string Password { getset; }    
  21.   
  22.     [DataType(DataType.Password)]    
  23.     [Display(Name = "Confirm password")]    
  24.     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]    
  25.     public string ConfirmPassword { getset; }    
  26. }  
Controller Part

Next in AccountController.cs first we get all the role names to be bound in ComboBox except Admin role and in register button click we will add the functionality to insert username and set user selected role in ASP.NET identity database.
 
 
 
Firstly, create an object for our ApplicationDBContext. Here, ApplicationDBContext is a class which is used to perform all ASP.NET Identity database functions like create user, roles, etc. 
  1. ApplicationDbContext context;  
  2.         public AccountController()  
  3.         {  
  4.             context = new ApplicationDbContext();  
  5.         }  
Register ActionResult method:

Using the ApplicationDBConterxt object we will get all the roles from database. For user registration we will not display the Admin roles. User can select rest of any role type during registration. 
  1. // GET: /Account/Register    
  2. [AllowAnonymous]    
  3. public ActionResult Register()    
  4. {    
  5.     ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))    
  6.                                     .ToList(), "Name""Name");    
  7.     return View();    
  8. }    
Register User

By default the user email will be stored as username in AspNetUsers table. Here we will change to store the user entered name. After user was created successfully we will set the user selected role for the user.
 
  1. // POST: /Account/Register    
  2. [HttpPost]    
  3. [AllowAnonymous]    
  4. [ValidateAntiForgeryToken]    
  5. public async Task<ActionResult> Register(RegisterViewModel model)    
  6. {    
  7.     if (ModelState.IsValid)    
  8.     {    
  9.         var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };    
  10.         var result = await UserManager.CreateAsync(user, model.Password);    
  11.         if (result.Succeeded)    
  12.         {    
  13.             await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);    
  14.   
  15.             // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771    
  16.             // Send an email with this link    
  17.             // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);    
  18.             // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);    
  19.             // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");    
  20.             //Assign Role to user Here       
  21.             await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles);    
  22.             //Ends Here     
  23.             return RedirectToAction("Index""Users");    
  24.         }    
  25.         ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))    
  26.                                   .ToList(), "Name""Name");    
  27.         AddErrors(result);    
  28.     }    
  29.   
  30.     // If we got this far, something failed, redisplay form    
  31.     return View(model);    
  32. }   
Customize User login

In the same way as user registration we will customize user login to change email as username to enter. By default in ASP.NET MVC 5 for login user needs to enter email and password. Here we will customize for user by entering username and password. In this demo we are not using any other Facebook, Gmail or Twitter login so we will be using UserName instead of Email.

View Part

Here we will change the email with UserName in Login.cshtml. We can find the Login.cshtml file from the folder inside Views/Account/Login.cshtml,

  1. @using shanuMVCUserRoles.Models  
  2. @model LoginViewModel  
  3. @{  
  4.     ViewBag.Title = "Log in";  
  5. }  
  6.   
  7. <h2>@ViewBag.Title</h2>  
  8. <div class="row">  
  9.     <div class="col-md-8">  
  10.         <section id="loginForm">  
  11.             @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal"role = "form" }))  
  12.             {  
  13.                 @Html.AntiForgeryToken()  
  14.                 <h4>Use a local account to log in.</h4>  
  15.                 <hr />  
  16.                 @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  17.                 <div class="form-group">  
  18.                     @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })  
  19.                     <div class="col-md-10">  
  20.                         @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })  
  21.                         @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })  
  22.                     </div>  
  23.                 </div>  
  24.                 <div class="form-group">  
  25.                     @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })  
  26.                     <div class="col-md-10">  
  27.                         @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  28.                         @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })  
  29.                     </div>  
  30.                 </div>  
  31.                 <div class="form-group">  
  32.                     <div class="col-md-offset-2 col-md-10">  
  33.                         <div class="checkbox">  
  34.                             @Html.CheckBoxFor(m => m.RememberMe)  
  35.                             @Html.LabelFor(m => m.RememberMe)  
  36.                         </div>  
  37.                     </div>  
  38.                 </div>  
  39.                 <div class="form-group">  
  40.                     <div class="col-md-offset-2 col-md-10">  
  41.                         <input type="submit" value="Log in" class="btn btn-default" />  
  42.                     </div>  
  43.                 </div>  
  44.                 <p>  
  45.                     @Html.ActionLink("Register as a new user", "Register")  
  46.                 </p>  
  47.                 @* Enable this once you have account confirmation enabled for password reset functionality  
  48.                     <p>  
  49.                         @Html.ActionLink("Forgot your password?", "ForgotPassword")  
  50.                     </p>*@  
  51. }  
  52.         </section>  
  53.     </div>  
  54.     <div class="col-md-4">  
  55.         <section id="socialLoginForm">  
  56.             @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })  
  57.         </section>  
  58.     </div>  
  59. </div>  
  60.   
  61. @section Scripts {  
  62.     @Scripts.Render("~/bundles/jqueryval")  
  63. }  
Model Part
 
Same as Registration in AccountViewModel we need to find the loginViewModel to change the Email with UserName,
 
 
Here in the following code we can see that we have changed the Email property to UserName. 
  1. public class LoginViewModel    
  2. {    
  3.     [Required]    
  4.     [Display(Name = "UserName")]    
  5.   
  6.     public string UserName { getset; }    
  7.   
  8.     [Required]    
  9.     [DataType(DataType.Password)]    
  10.     [Display(Name = "Password")]    
  11.     public string Password { getset; }    
  12.   
  13.     [Display(Name = "Remember me?")]    
  14.     public bool RememberMe { getset; }    
  15. }    
Controller Part:

In login button click we need to change the email with username to check from database for user Authentication. Here in the following code we can see as we changed the email with username after successful login we will be redirect to the user page. Next we will see how to create a user page and display the text and menu by user role.
 
  1. // POST: /Account/Login    
  2. [HttpPost]    
  3. [AllowAnonymous]    
  4. [ValidateAntiForgeryToken]    
  5. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)    
  6. {    
  7.     if (!ModelState.IsValid)    
  8.     {    
  9.         return View(model);    
  10.     }    
  11.   
  12.     // This doesn't count login failures towards account lockout    
  13.     // To enable password failures to trigger account lockout, change to shouldLockout: true    
  14.     var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);    
  15.     switch (result)    
  16.     {    
  17.         case SignInStatus.Success:    
  18.             return RedirectToLocal(returnUrl);    
  19.         case SignInStatus.LockedOut:    
  20.             return View("Lockout");    
  21.         case SignInStatus.RequiresVerification:    
  22.             return RedirectToAction("SendCode"new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });    
  23.         case SignInStatus.Failure:    
  24.         default:    
  25.             ModelState.AddModelError("""Invalid login attempt.");    
  26.             return View(model);    
  27.     }    
  28. }    
  29.   
  30. //    
  31. // GET: /Account/VerifyCode    
  32. [AllowAnonymous]    
  33. public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)    
  34. {    
  35.     // Require that the user has already logged in via username/password or external login    
  36.     if (!await SignInManager.HasBeenVerifiedAsync())    
  37.     {    
  38.         return View("Error");    
  39.     }    
  40.     return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });    
  41. }    
Authenticated and Authorized User page

Here we create a new page for displaying message of Authenticated and Authorized user by their role.

If the logged in user role is Admin, then we will display the welcome message for Admin and display the menu forcreating new roles.

If the logged in users roles are Manager, Employee, Accounts, etc. then we will display a welcome message for them.

Firstly, create a new Empty Controller named “userscontroller.cs”. In this controller first we add the [Authorize] at the top of controller for checking the valid users.

Creating our View: Right click on index ActionResult and create a view .

In view we check for the ViewBag.displayMenu value. If the value is “Yes", then we display the Admin welcome message and a link for creating new Menu. If the ViewBag.displayMenu is “No, then display other users name with welcome message.

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5.   
  6.   
  7. @if (ViewBag.displayMenu == "Yes")  
  8. {  
  9.     <h1>Welcome Admin. Now you can create user Role.</h1>  
  10.     <h3>  
  11.         <li>@Html.ActionLink("Manage Role", "Index", "Role")</li>  
  12.     </h3>  
  13. }  
  14. else  
  15. {  
  16.     <h2>  Welcome <strong>@ViewBag.Name</strong> :) .We will add user module soon </h2>  
  17. }  
Controller part

In controller we will check the user is logged in to the system or not. If the user did not log in, then

Display the message as “Not Logged In” and if the user is authenticated, then we check the logged in users role. If the users role is “Admin", then we set ViewBag.displayMenu = "Yes", else we set ViewBag.displayMenu = "No"

  1. public ActionResult Index()    
  2. {    
  3.     if (User.Identity.IsAuthenticated)    
  4.     {    
  5.         var user = User.Identity;    
  6.         ViewBag.Name = user.Name;    
  7.         
  8.         ViewBag.displayMenu = "No";    
  9.   
  10.         if (isAdminUser())    
  11.         {    
  12.             ViewBag.displayMenu = "Yes";    
  13.         }    
  14.         return View();    
  15.     }    
  16.     else    
  17.     {    
  18.         ViewBag.Name = "Not Logged IN";    
  19.     }    
  20.     return View();    
  21.   
  22. }    

For checking the user is logged in we create method and return the Boolean value to our main Index method. 

  1. public Boolean isAdminUser()    
  2. {    
  3.     if (User.Identity.IsAuthenticated)    
  4.     {    
  5.         var user = User.Identity;    
  6.         ApplicationDbContext context = new ApplicationDbContext();    
  7.         var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));    
  8.         var s = UserManager.GetRoles(user.GetUserId());    
  9.         if (s[0].ToString() == "Admin")    
  10.         {    
  11.             return true;    
  12.         }    
  13.         else    
  14.         {    
  15.             return false;    
  16.         }    
  17.     }    
  18.     return false;    
  19. }    
Admin users can create Roles

We already saw that if the Admin user is logged in then we will display the link for creating new users. For admin login we have already created a default user with UserName as "shanu" and password as "A@Z200711",

 
For creating user role by admin first we will add a new empty controller and named it RoleController.cs,

In this controller we check that the user role is Admin. If the logged in user role is Admin, then we will get all the role names using ApplicationDbContext object. 

  1. public ActionResult Index()    
  2. {    
  3.   
  4.     if (User.Identity.IsAuthenticated)    
  5.     {    
  6.   
  7.   
  8.         if (!isAdminUser())    
  9.         {    
  10.             return RedirectToAction("Index""Home");    
  11.         }    
  12.     }    
  13.     else    
  14.     {    
  15.         return RedirectToAction("Index""Home");    
  16.     }    
  17.   
  18.     var Roles = context.Roles.ToList();    
  19.     return View(Roles);    
  20.   
  21. }     
In view we bind all the user roles inside html table. 
  1. @model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>  
  2. @{  
  3.     ViewBag.Title = "Add Role";  
  4. }  
  5. <table style=" background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="6" cellspacing="6">  
  6.     <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  7.         <td align="center" colspan="2">  
  8.             <h2> Create User Roles</h2>  
  9.         </td>  
  10.   
  11.     </tr>  
  12.   
  13.     <tr>  
  14.         <td>  
  15.             <table id="tbrole" style="width:100%; border:dotted 1px; background-color:gainsboro; padding-left:10px;">  
  16.   
  17.                 @foreach (var item in Model)  
  18.                 {  
  19.                     <tr>  
  20.                         <td style="width:100%; border:dotted 1px;">  
  21.                             @item.Name  
  22.                         </td>  
  23.                     </tr>}  
  24.             </table>  
  25.         </td>  
  26.         <td align="right" style="color:#FFFFFF;padding-right:10;">  
  27.   
  28.   
  29.             <h3>   @Html.ActionLink("Click to Create New Role", "Create", "Role") </h3>  
  30.         </td>  
  31.     </tr>  
  32. </table>  
Conclusion

Firstly, create a sample AttendanceDB Database in your SQL Server. In the Web.Config file change the DefaultConnection connection string with your SQL Server Connections. In Startup.cs file I have created default Admin user with UserName "shanu" and password "A@Z200711." This UserName and password will be used to login as Admin user. You can change this user name and password as you like. For security reasons after logging in as Admin you can change the Admin user password as you like,