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:
- A SP.NET MVC 5 Security and Creating User Role
- 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.
- USE Master;
- IF EXISTS (SELECT [ name ] FROM sys.databases WHERE [ name ] = 'AttendanceDB' )
- BEGIN
- Change DATABASE AttendanceDB Ready SINGLE_USER WITH ROLLBACK IMMEDIATE
- Driblet DATABASE AttendanceDB ;
- END
- CREATE DATABASE AttendanceDB
- Become
- USE AttendanceDB
- Become
Spider web.Config In spider web.config file we can find the
Here in connection cord alter your SQL Server Name, UID and PWD to create and store all user details in one database.
- < connectionStrings >
- < add name = "DefaultConnection" connectionString = "data source=YOURSERVERNAME;initial itemize=AttendanceDB;user id=UID;password=PWD;Integrated Security=True" providerName = "System.Data.SqlClient" />
- </ 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.
- public void Configuration(IAppBuilder app)
- {
- ConfigureAuth(app);
- createRolesandUsers();
- }
- private void createRolesandUsers()
- {
- ApplicationDbContext context =new ApplicationDbContext();
- var roleManager =new RoleManager<IdentityRole>( new RoleStore<IdentityRole>(context));
- var UserManager =new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(context));
- if (!roleManager.RoleExists( "Admin" ))
- {
- var office =new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
- function.Name ="Admin" ;
- roleManager.Create(function);
- var user =new ApplicationUser();
- user.UserName ="shanu" ;
- user.Email ="syedshanumcain@gmail.com" ;
- string userPWD = "A@Z200711" ;
- var chkUser = UserManager.Create(user, userPWD);
- if (chkUser.Succeeded)
- {
- var result1 = UserManager.AddToRole(user.Id,"Admin" );
- }
- }
- if (!roleManager.RoleExists( "Manager" ))
- {
- var role =new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
- role.Proper name ="Manager" ;
- roleManager.Create(role);
- }
- if (!roleManager.RoleExists( "Employee" ))
- {
- var role =new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
- role.Proper noun ="Employee" ;
- roleManager.Create(office);
- }
- }
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.
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.
- @model shanuMVCUserRoles.Models.RegisterViewModel
- @{
- ViewBag.Title = "Register" ;
- }
- < h2 > @ViewBag.Championship. </ h2 >
- @using (Html.BeginForm("Annals", "Business relationship", FormMethod.Post, new { @class = "form-horizontal" , role = "form" }))
- {
- @Html.AntiForgeryToken()
- < h4 > Create a new account. </ h4 >
- < hr />
- @Html.ValidationSummary("", new { @grade = "text-danger" })
- < div course = "form-group" >
- @Html.LabelFor(1000 = > m.Email, new { @ form = "col-md-2 control-label" })
- < div class = "col-doctor-x" >
- @Html.TextBoxFor(chiliad = > m.Email, new { @ class = "class-control" })
- </ div >
- </ div >
- < div class = "form-grouping" >
- @Html.LabelFor(m = > m.UserName, new { @ class = "col-doctor-2 control-label" })
- < div class = "col-md-10" >
- @Html.TextBoxFor(grand = > m.UserName, new { @ course = "form-control" })
- </ div >
- </ div >
- < div class = "form-group" >
- @Html.LabelFor(m = > m.Password, new { @ class = "col-doc-2 control-label" })
- < div grade = "col-medico-ten" >
- @Html.PasswordFor(g = > m.Password, new { @ grade = "form-control" })
- </ div >
- </ div >
- < div form = "form-group" >
- @Html.LabelFor(m = > m.ConfirmPassword, new { @ grade = "col-md-ii control-label" })
- < div class = "col-md-10" >
- @Html.PasswordFor(m = > m.ConfirmPassword, new { @ course = "form-control" })
- </ div >
- </ div >
- < div course = "form-group" >
- @Html.Label("user Office", new { @course = "col-md-two control-characterization" })
- < div form = "col-md-ten" >
- @*@Html.DropDownList("Name")*@
- @Html.DropDownList("UserRoles", (SelectList)ViewBag.Proper name, " ")
- </ div >
- </ div >
- < div class = "form-group" >
- < div class = "col-md-kickoff-2 col-md-ten" >
- < input type = "submit" class = "btn btn-default" value = "Register" />
- </ div >
- </ div >
- }
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
Model Office
Next in AccountViewModel.cs check for the RegisterViewModel and add the UserRoles and UserName properties with required for validation.
Double click theAccountViewModel.cs file from Models folder, find the RegisterViewModel class, add UserName and UserRoles properties every bit in the following.
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.
- ApplicationDbContext context;
- public AccountController()
- {
- context =new ApplicationDbContext();
- }
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.
- [AllowAnonymous]
- public ActionResult Register()
- {
- ViewBag.Name =new SelectList(context.Roles.Where(u => !u.Name.Contains( "Admin" ))
- .ToList(),"Name" , "Proper noun" );
- return View();
- }
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.
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 ,
- @using shanuMVCUserRoles.Models
- @model LoginViewModel
- @{
- ViewBag.Title = "Log in" ;
- }
- < h2 > @ViewBag.Championship </ h2 >
- < div course = "row" >
- < div class = "col-physician-8" >
- < section id = "loginForm" >
- @using (Html.BeginForm("Login", "Account", new {ReturnUrl = ViewBag .ReturnUrl }, FormMethod.Post, new { @ class = "form-horizontal" , role = "class" }))
- {
- @Html.AntiForgeryToken()
- < h4 > Use a local account to log in. </ h4 >
- < hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- < div class = "form-group" >
- @Html.LabelFor(m = > m.UserName, new { @ class = "col-md-two control-characterization" })
- < div class = "col-md-ten" >
- @Html.TextBoxFor(m = > m.UserName, new { @ form = "form-control" })
- @Html.ValidationMessageFor(yard = > m.UserName, "", new { @ class = "text-danger" })
- </ div >
- </ div >
- < div class = "grade-grouping" >
- @Html.LabelFor(m = > m.Password, new { @ class = "col-md-2 control-label" })
- < div class = "col-doc-10" >
- @Html.PasswordFor(grand = > k.Countersign, new { @ grade = "form-control" })
- @Html.ValidationMessageFor(g = > 1000.Countersign, "", new { @ class = "text-danger" })
- </ div >
- </ div >
- < div class = "form-group" >
- < div class = "col-md-offset-2 col-doctor-10" >
- < div class = "checkbox" >
- @Html.CheckBoxFor(thou = > m.RememberMe)
- @Html.LabelFor(k = > grand.RememberMe)
- </ div >
- </ div >
- </ div >
- < div class = "grade-group" >
- < div grade = "col-dr.-offset-ii col-medico-x" >
- < input blazon = "submit" value = "Log in" class = "btn btn-default" />
- </ div >
- </ div >
- < p >
- @Html.ActionLink("Annals as a new user", "Register")
- </ p >
- @* Enable this once y'all take account confirmation enabled for password reset functionality
- < p >
- @Html.ActionLink("Forgot your password?", "ForgotPassword")
- </ p > *@
- }
- </ section >
- </ div >
- < div form = "col-md-four" >
- < section id = "socialLoginForm" >
- @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel {ReturnUrl = ViewBag .ReturnUrl })
- </ department >
- </ div >
- </ div >
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
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.
- public class LoginViewModel
- {
- [Required]
- [Display(Name ="UserName" )]
- public string UserName { get ; fix ; }
- [Required]
- [DataType(DataType.Password)]
- [Display(Name ="Password" )]
- public string Password { get ; ready ; }
- [Display(Name ="Remember me?" )]
- public bool RememberMe { get ; set ; }
- }
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.
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Login(LoginViewModel model, cord returnUrl)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- var event = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout:faux );
- switch (result)
- {
- example SignInStatus.Success:
- return RedirectToLocal(returnUrl);
- instance SignInStatus.LockedOut:
- return View( "Lockout" );
- case SignInStatus.RequiresVerification:
- return RedirectToAction( "SendCode" , new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
- case SignInStatus.Failure:
- default :
- ModelState.AddModelError("" , "Invalid login attempt." );
- return View(model);
- }
- }
- [AllowAnonymous]
- public async Task<ActionResult> VerifyCode( string provider, string returnUrl, bool rememberMe)
- {
- if (!await SignInManager.HasBeenVerifiedAsync())
- {
- return View( "Fault" );
- }
- render View( new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
- }
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.
- @{
- ViewBag.Title = "Alphabetize" ;
- }
- @if (ViewBag.displayMenu == "Yes")
- {
- < h1 > Welcome Admin. Now you can create user Role. </ h1 >
- < h3 >
- < li > @Html.ActionLink("Manage Role", "Index", "Function") </ li >
- </ h3 >
- }
- else
- {
- < h2 > Welcome < strong > @ViewBag.Name </ strong > :) .We will add user module before long </ h2 >
- }
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".
- public ActionResult Index()
- {
- if (User.Identity.IsAuthenticated)
- {
- var user = User.Identity;
- ViewBag.Name = user.Name;
- ViewBag.displayMenu ="No" ;
- if (isAdminUser())
- {
- ViewBag.displayMenu ="Yes" ;
- }
- return View();
- }
- else
- {
- ViewBag.Proper noun ="Non Logged IN" ;
- }
- return View();
- }
For checking the user is logged in we create method and render the Boolean value to our chief Alphabetize method.
- public Boolean isAdminUser()
- {
- if (User.Identity.IsAuthenticated)
- {
- var user = User.Identity;
- ApplicationDbContext context =new ApplicationDbContext();
- var UserManager =new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(context));
- var s = UserManager.GetRoles(user.GetUserId());
- if (s[0].ToString() == "Admin" )
- {
- return true ;
- }
- else
- {
- render fake ;
- }
- }
- return false ;
- }
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.
- public ActionResult Index()
- {
- if (User.Identity.IsAuthenticated)
- {
- if (!isAdminUser())
- {
- return RedirectToAction( "Alphabetize" , "Home" );
- }
- }
- else
- {
- return RedirectToAction( "Index" , "Habitation" );
- }
- var Roles = context.Roles.ToList();
- return View(Roles);
- }
In view nosotros demark all the user roles within html tabular array.
- @model IEnumerable < Microsoft.AspNet.Identity.EntityFramework.IdentityRole >
- @{
- ViewBag.Title = "Add Role" ;
- }
- < table style = " background-colour:#FFFFFF; border: dashed 3px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding = "6" cellspacing = "six" >
- < tr style = "height: 30px; groundwork-colour:#336699 ; colour:#FFFFFF ;border: solid 1px #659EC7;" >
- < td marshal = "middle" colspan = "2" >
- < h2 > Create User Roles </ h2 >
- </ td >
- </ tr >
- < tr >
- < td >
- < table id = "tbrole" mode = "width:100%; border:dotted 1px; background-color:gainsboro; padding-left:10px;" >
- @foreach (var item in Model)
- {
- < tr >
- < td style = "width:100%; border:dotted 1px;" >
- @item.Proper noun
- </ td >
- </ tr > }
- </ table >
- </ td >
- < td marshal = "right" style = "color:#FFFFFF;padding-right:x;" >
- < h3 > @Html.ActionLink("Click to Create New Role", "Create", "Role") </ h3 >
- </ td >
- </ tr >
- </ 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