banner



How To Use Local User Groups To Restrict Access To Asp.net Controller


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 serial nosotros volition come across:

  1. A SP.NET MVC 5 Security and Creating User Role
  2. User Part base of operations Menu Direction (Dynamic menu using MVC and AngularJS)

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

Here we volition run into 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 Electronic mail with User Proper name .
  • Display Role Cosmos Card but for Admin User .
  • Brandish message for normal user .
  • Redirect Unauthenticated users to default home page .

Authentication and Authorisation

Authentication

Check for the Valid User. Here the question is how to cheque whether a user is valid or not. When a user comes to a website for the first time he volition annals for that website. All his information, like user proper noun, countersign, email, and so on volition be stored in the website database. When a user enters his userID and password, the data will be checked with the database. If the user has entered the same userID and Countersign equally in the database and 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 non friction match the database and so the login folio will give a message, something like "Enter valid Name or Password". The entire procedure of checking whether the user is valid or non for accessing the website is called Hallmark.

Authorization

In one case the user is authenticated he needs to exist 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 Auditor is logged in, then he is to exist redirected to his Accounts folio. If an End User is logged in, then he is to be redirected to his page.

Prerequisites

Visual Studio 2015: You can download information technology from here .

Using the code

Create your Web Awarding in Visual Studio 2015

After installing our Visual Studio 2015 click Get-go, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, so Project, select Web and and so select ASP.Cyberspace 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. Nosotros volition exist using this database for ASP.Internet Identity table creation and as well our sample attendance Web project. Instead of using two databases as one for default ASP.NET user database and another for our Omnipresence DB, here we will be using one common database for both user details and for our sample web projection demo.

Create Database: Run the post-obit and create database script to create our sample test database.

  1. USE Master;
  2. IF EXISTS (SELECT  [ name ] FROM  sys.databases WHERE  [ name ] = 'AttendanceDB'  )
  3. BEGIN
  4. Change DATABASE  AttendanceDB Ready  SINGLE_USER WITH ROLLBACK  IMMEDIATE
  5. Driblet DATABASE  AttendanceDB ;
  6. END
  7. CREATE DATABASE  AttendanceDB
  8. Become
  9. USE AttendanceDB
  10. Become

Spider web.Config

In spider web.config file we can find the

DefaultConnection Connection string. Past default ASP.NET MVC will use this connection cord to create all ASP.Net Identity related tables like AspNetUsers, etc. For our awarding nosotros too need to utilise database for other page activities instead of using two unlike databases, ane for User details and one for our own functionality. Here I will be using one database where all ASP.Internet Identity tables will be created and also we tin can create our own tables for other folio uses.

Here in connection cord alter 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 itemize=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","Managing director", etc and also nosotros volition 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 betwixt .Internet and Web Server and each OWIN application has a Startup Class where we can specify components.

Reference

  • OWIN and Katana

In "Startup.cs" file we can detect the Configuration method. From this method we volition be calling our createRolesandUsers() method to create a default user role and user.We will cheque for Roles already created or not. If Roles, like Admin, is not created, and so we will create a new Part every bit "Admin" and we volition create a default user and set the user role every bit Admin. We volition be using this user every bit super user where the user can create new roles from our MVC awarding.

  1. public void  Configuration(IAppBuilder app)
  2. {
  3.     ConfigureAuth(app);
  4.     createRolesandUsers();
  5. }
  6. private void  createRolesandUsers()
  7. {
  8.     ApplicationDbContext context =new  ApplicationDbContext();
  9.     var roleManager =new  RoleManager<IdentityRole>( new  RoleStore<IdentityRole>(context));
  10.     var UserManager =new  UserManager<ApplicationUser>( new  UserStore<ApplicationUser>(context));
  11. if  (!roleManager.RoleExists( "Admin" ))
  12.     {
  13.         var office =new  Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
  14.         function.Name ="Admin" ;
  15.         roleManager.Create(function);
  16.         var user =new  ApplicationUser();
  17.         user.UserName ="shanu" ;
  18.         user.Email ="syedshanumcain@gmail.com" ;
  19. string  userPWD = "A@Z200711" ;
  20.         var chkUser = UserManager.Create(user, userPWD);
  21. if  (chkUser.Succeeded)
  22.         {
  23.             var result1 = UserManager.AddToRole(user.Id,"Admin" );
  24.         }
  25.     }
  26. if  (!roleManager.RoleExists( "Manager" ))
  27.     {
  28.         var role =new  Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
  29.         role.Proper name ="Manager" ;
  30.         roleManager.Create(role);
  31.     }
  32. if  (!roleManager.RoleExists( "Employee" ))
  33.     {
  34.         var role =new  Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
  35.         role.Proper noun ="Employee" ;
  36.         roleManager.Create(office);
  37.     }
  38. }

When we run our awarding we can see new default ASP.Net user related tables volition be created in our AttendanceDB Database. Here nosotros tin see in the following image equally all ASP.NET user related tables will exist automatically created when nosotros run our application and also all our default user roles will be inserted in AspNetRoles tabular array and default admin user will be created in AspNetUsers tabular array.

query result

Customize User Registration with adding username and Office

Past default for user registration in ASP.Net MVC 5 nosotros tin use email and passoword. Here, we will customize the default user registration with adding a username and a ComboBox to brandish the user roles. User can enter their username and select there user role during registration.

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

Double click the Register.cshtml and change the html lawmaking like the post-obit to add textbox and combobox with caption. Hither nosotros tin can run into offset nosotros 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. < h2 > @ViewBag.Championship. </ h2 >
  6. @using (Html.BeginForm("Annals", "Business relationship", FormMethod.Post, new { @class  = "form-horizontal" , role  = "form"  }))
  7. {
  8.     @Html.AntiForgeryToken()
  9. < h4 > Create a new account. </ h4 >
  10. < hr />
  11.     @Html.ValidationSummary("", new { @grade  = "text-danger"  })
  12. < div course = "form-group" >
  13.         @Html.LabelFor(1000  = >  m.Email, new { @ form  = "col-md-2 control-label"  })
  14. < div class = "col-doctor-x" >
  15.             @Html.TextBoxFor(chiliad  = >  m.Email, new { @ class  = "class-control"  })
  16. </ div >
  17. </ div >
  18. < div class = "form-grouping" >
  19.         @Html.LabelFor(m  = >  m.UserName, new { @ class  = "col-doctor-2 control-label"  })
  20. < div class = "col-md-10" >
  21.             @Html.TextBoxFor(grand  = >  m.UserName, new { @ course  = "form-control"  })
  22. </ div >
  23. </ div >
  24. < div class = "form-group" >
  25.         @Html.LabelFor(m  = >  m.Password, new { @ class  = "col-doc-2 control-label"  })
  26. < div grade = "col-medico-ten" >
  27.             @Html.PasswordFor(g  = >  m.Password, new { @ grade  = "form-control"  })
  28. </ div >
  29. </ div >
  30. < div form = "form-group" >
  31.         @Html.LabelFor(m  = >  m.ConfirmPassword, new { @ grade  = "col-md-ii control-label"  })
  32. < div class = "col-md-10" >
  33.             @Html.PasswordFor(m  = >  m.ConfirmPassword, new { @ course  = "form-control"  })
  34. </ div >
  35. </ div >
  36. < div course = "form-group" >
  37.         @Html.Label("user Office", new { @course  = "col-md-two control-characterization"  })
  38. < div form = "col-md-ten" >
  39.             @*@Html.DropDownList("Name")*@
  40.             @Html.DropDownList("UserRoles", (SelectList)ViewBag.Proper name, " ")
  41. </ div >
  42. </ div >
  43. < div class = "form-group" >
  44. < div class = "col-md-kickoff-2 col-md-ten" >
  45. < input type = "submit" class = "btn btn-default" value = "Register" />
  46. </ div >
  47. </ div >
  48. }
  49. @section Scripts {
  50.     @Scripts.Render("~/bundles/jqueryval")
  51. }

Model Office

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 every bit in the following.

  1. public grade  RegisterViewModel
  2. {
  3.     [Required]
  4.     [Display(Name ="UserRoles" )]
  5. public cord  UserRoles { go ; prepare ; }
  6.     [Required]
  7.     [EmailAddress]
  8.     [Brandish(Proper name ="Email" )]
  9. public string  E-mail { get ; fix ; }
  10.     [Required]
  11.     [Display(Name ="UserName" )]
  12. public string  UserName { get ; ready ; }
  13.     [Required]
  14.     [StringLength(100, ErrorMessage ="The {0} must be at least {2} characters long." , MinimumLength = half dozen)]
  15.     [DataType(DataType.Password)]
  16.     [Display(Proper name ="Password" )]
  17. public string  Password { go ; gear up ; }
  18.     [DataType(DataType.Password)]
  19.     [Display(Name ="Confirm password" )]
  20.     [Compare("Password" , ErrorMessage = "The password and confirmation countersign do not friction match." )]
  21. public string  ConfirmPassword { get ; ready ; }
  22. }

Controller Part

Next in AccountController.cs first we get all the role names to be leap in ComboBox except Admin office and in register button click we will add the functionality to insert username and set user selected part in ASP.NET identity database.

Firstly, create an object for our ApplicationDBContext. Here, ApplicationDBContext is a class which is used to perform all ASP.Internet Identity database functions like create user, roles, etc.

  1. ApplicationDbContext context;
  2. public  AccountController()
  3.         {
  4.             context =new  ApplicationDbContext();
  5.         }

Annals ActionResult method:

Using the ApplicationDBConterxt object we volition become all the roles from database. For user registration we will non brandish the Admin roles. User can select rest of whatsoever role blazon during registration.

  1. [AllowAnonymous]
  2. public  ActionResult Register()
  3. {
  4.     ViewBag.Name =new  SelectList(context.Roles.Where(u => !u.Name.Contains( "Admin" ))
  5.                                     .ToList(),"Name" , "Proper noun" );
  6. return  View();
  7. }

Register User

By default the user e-mail will be stored as username in AspNetUsers tabular array. Here we will modify to store the user entered name. Later on user was created successfully we volition prepare the user selected function for the user.

  1. [HttpPost]
  2. [AllowAnonymous]
  3. [ValidateAntiForgeryToken]
  4. public  async Task<ActionResult> Register(RegisterViewModel model)
  5. {
  6. if  (ModelState.IsValid)
  7.     {
  8.         var user =new  ApplicationUser { UserName = model.UserName, Email = model.Email };
  9.         var result = await UserManager.CreateAsync(user, model.Password);
  10. if  (result.Succeeded)
  11.         {
  12.             await SignInManager.SignInAsync(user, isPersistent:fake , rememberBrowser: false );
  13.             awaitthis .UserManager.AddToRoleAsync(user.Id, model.UserRoles);
  14. return  RedirectToAction( "Index" , "Users" );
  15.         }
  16.         ViewBag.Name =new  SelectList(context.Roles.Where(u => !u.Name.Contains( "Admin" ))
  17.                                   .ToList(),"Name" , "Name" );
  18.         AddErrors(result);
  19.     }
  20. return  View(model);
  21. }

Customize User login

In the same way every bit user registration we will customize user login to change e-mail as username to enter. By default in ASP.NET MVC 5 for login user needs to enter e-mail and password. Hither we will customize for user past entering username and countersign. In this demo we are non using whatsoever other Facebook, Gmail or Twitter login so we will be using UserName instead of E-mail.

View Part

Here nosotros volition modify the email with UserName in Login.cshtml. We can find the Login.cshtml file from the binder inside Views/Account/Login.cshtml ,

  1. @using shanuMVCUserRoles.Models
  2. @model LoginViewModel
  3. @{
  4. ViewBag.Title  = "Log in" ;
  5. }
  6. < h2 > @ViewBag.Championship </ h2 >
  7. < div course = "row" >
  8. < div class = "col-physician-8" >
  9. < section id = "loginForm" >
  10.             @using (Html.BeginForm("Login", "Account", new {ReturnUrl  = ViewBag .ReturnUrl }, FormMethod.Post, new { @ class  = "form-horizontal" , role  = "class"  }))
  11.             {
  12.                 @Html.AntiForgeryToken()
  13. < h4 > Use a local account to log in. </ h4 >
  14. < hr />
  15.                 @Html.ValidationSummary(true, "", new { @class  = "text-danger"  })
  16. < div class = "form-group" >
  17.                     @Html.LabelFor(m  = >  m.UserName, new { @ class  = "col-md-two control-characterization"  })
  18. < div class = "col-md-ten" >
  19.                         @Html.TextBoxFor(m  = >  m.UserName, new { @ form  = "form-control"  })
  20.                         @Html.ValidationMessageFor(yard  = >  m.UserName, "", new { @ class  = "text-danger"  })
  21. </ div >
  22. </ div >
  23. < div class = "grade-grouping" >
  24.                     @Html.LabelFor(m  = >  m.Password, new { @ class  = "col-md-2 control-label"  })
  25. < div class = "col-doc-10" >
  26.                         @Html.PasswordFor(grand  = >  k.Countersign, new { @ grade  = "form-control"  })
  27.                         @Html.ValidationMessageFor(g  = >  1000.Countersign, "", new { @ class  = "text-danger"  })
  28. </ div >
  29. </ div >
  30. < div class = "form-group" >
  31. < div class = "col-md-offset-2 col-doctor-10" >
  32. < div class = "checkbox" >
  33.                             @Html.CheckBoxFor(thou  = >  m.RememberMe)
  34.                             @Html.LabelFor(k  = >  grand.RememberMe)
  35. </ div >
  36. </ div >
  37. </ div >
  38. < div class = "grade-group" >
  39. < div grade = "col-dr.-offset-ii col-medico-x" >
  40. < input blazon = "submit" value = "Log in" class = "btn btn-default" />
  41. </ div >
  42. </ div >
  43. < p >
  44.                     @Html.ActionLink("Annals as a new user", "Register")
  45. </ p >
  46.                 @* Enable this once y'all take account confirmation enabled for password reset functionality
  47. < p >
  48.                         @Html.ActionLink("Forgot your password?", "ForgotPassword")
  49. </ p > *@
  50. }
  51. </ section >
  52. </ div >
  53. < div form = "col-md-four" >
  54. < section id = "socialLoginForm" >
  55.             @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel {ReturnUrl  = ViewBag .ReturnUrl })
  56. </ department >
  57. </ div >
  58. </ div >
  59. @section Scripts {
  60.     @Scripts.Render("~/bundles/jqueryval")
  61. }

Model Part

Aforementioned as Registration in AccountViewModel we need to find the loginViewModel to change the Email with UserName,

Hither in the following lawmaking nosotros can see that nosotros accept changed the E-mail property to UserName.

  1. public class  LoginViewModel
  2. {
  3.     [Required]
  4.     [Display(Name ="UserName" )]
  5. public string  UserName { get ; fix ; }
  6.     [Required]
  7.     [DataType(DataType.Password)]
  8.     [Display(Name ="Password" )]
  9. public string  Password { get ; ready ; }
  10.     [Display(Name ="Remember me?" )]
  11. public bool  RememberMe { get ; set ; }
  12. }

Controller Part:

In login button click we need to change the email with username to bank check from database for user Authentication. Hither in the following code we tin meet every bit we changed the email with username afterwards successful login we volition be redirect to the user page. Adjacent we will see how to create a user page and display the text and card by user office.

  1. [HttpPost]
  2. [AllowAnonymous]
  3. [ValidateAntiForgeryToken]
  4. public  async Task<ActionResult> Login(LoginViewModel model, cord  returnUrl)
  5. {
  6. if  (!ModelState.IsValid)
  7.     {
  8. return  View(model);
  9.     }
  10.     var event = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout:faux );
  11. switch  (result)
  12.     {
  13. example  SignInStatus.Success:
  14. return  RedirectToLocal(returnUrl);
  15. instance  SignInStatus.LockedOut:
  16. return  View( "Lockout" );
  17. case  SignInStatus.RequiresVerification:
  18. return  RedirectToAction( "SendCode" , new  { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  19. case  SignInStatus.Failure:
  20. default :
  21.             ModelState.AddModelError("" , "Invalid login attempt." );
  22. return  View(model);
  23.     }
  24. }
  25. [AllowAnonymous]
  26. public  async Task<ActionResult> VerifyCode( string  provider, string  returnUrl, bool  rememberMe)
  27. {
  28. if  (!await SignInManager.HasBeenVerifiedAsync())
  29.     {
  30. return  View( "Fault" );
  31.     }
  32. render  View( new  VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  33. }

Authenticated and Authorized User page

Here we create a new page for displaying message of Authenticated and Authorized user past 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 Managing director, Employee, Accounts, etc. then we will display a welcome message for them.

Firstly, create a new Empty Controller named "userscontroller.cs". In this controller get-go nosotros add together the [Qualify] at the top of controller for checking the valid users.

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

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

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

Controller part

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

Brandish the message as "Not Logged In" and if the user is authenticated, then we bank check the logged in users role. If the users role is "Admin", then nosotros 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.         ViewBag.displayMenu ="No" ;
  8. if  (isAdminUser())
  9.         {
  10.             ViewBag.displayMenu ="Yes" ;
  11.         }
  12. return  View();
  13.     }
  14. else
  15.     {
  16.         ViewBag.Proper noun ="Non Logged IN" ;
  17.     }
  18. return  View();
  19. }

For checking the user is logged in we create method and render the Boolean value to our chief Alphabetize 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. render fake ;
  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 brandish the link for creating new users. For admin login we have already created a default user with UserName equally "shanu" and password every bit "A@Z200711",

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

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

  1. public  ActionResult Index()
  2. {
  3. if  (User.Identity.IsAuthenticated)
  4.     {
  5. if  (!isAdminUser())
  6.         {
  7. return  RedirectToAction( "Alphabetize" , "Home" );
  8.         }
  9.     }
  10. else
  11.     {
  12. return  RedirectToAction( "Index" , "Habitation" );
  13.     }
  14.     var Roles = context.Roles.ToList();
  15. return  View(Roles);
  16. }

In view nosotros demark all the user roles within html tabular array.

  1. @model IEnumerable < Microsoft.AspNet.Identity.EntityFramework.IdentityRole >
  2. @{
  3. ViewBag.Title  = "Add Role" ;
  4. }
  5. < table style = " background-colour:#FFFFFF; border: dashed 3px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding = "6" cellspacing = "six" >
  6. < tr style = "height: 30px; groundwork-colour:#336699 ; colour:#FFFFFF ;border: solid 1px #659EC7;" >
  7. < td marshal = "middle" colspan = "2" >
  8. < h2 >  Create User Roles </ h2 >
  9. </ td >
  10. </ tr >
  11. < tr >
  12. < td >
  13. < table id = "tbrole" mode = "width:100%; border:dotted 1px; background-color:gainsboro; padding-left:10px;" >
  14.                 @foreach (var item in Model)
  15.                 {
  16. < tr >
  17. < td style = "width:100%; border:dotted 1px;" >
  18.                             @item.Proper noun
  19. </ td >
  20. </ tr > }
  21. </ table >
  22. </ td >
  23. < td marshal = "right" style = "color:#FFFFFF;padding-right:x;" >
  24. < h3 >    @Html.ActionLink("Click to Create New Role", "Create", "Role") </ h3 >
  25. </ td >
  26. </ tr >
  27. </ 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 countersign "A@Z200711."This UserName and password volition exist used to login as Admin user. Yous tin modify this user name and password as you like. For security reasons later logging in every bit Admin y'all tin change the Admin user password as you like,

How To Use Local User Groups To Restrict Access To Asp.net Controller,

Source: https://www.c-sharpcorner.com/UploadFile/asmabegam/Asp-Net-mvc-5-security-and-creating-user-role/

Posted by: stoverhoatherand.blogspot.com

0 Response to "How To Use Local User Groups To Restrict Access To Asp.net Controller"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel