Skip to main content

Role-Based Authorization in ASP.NET MVC


Role-Based Authorization Explained

The most challenge aspect of any web application is implementing its security. In traditional web development with ASP.NET (from version 2.0 onwards), we have been using Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization. But with an increase in social networking and global authentication providers, we needed an upgraded membership system.
ASP.NET Identity is the new membership system for building ASP.NET web applications, phone, store, or hybrid applications using social identities for authentication and authorization. So we can now use Windows Live (e.g. Hotmail), Gmail, Facebook and Twitter for authentication before the user starts using our web application.
For internal application, we need to create users and roles for providing users access to creating items, products or managing other users. Necessary references are provided by MVC 5 applications for ASP.NET Identity. This allows to use external login using Live, etc. services and also allows us to create Roles and Users for internal application.

Implementing ASP.NET Identity

We are going to implement Role-Based Authorization using the application created in the previous article ASP.NETMVC Security System.

Open the above application in visual studio and make some changes to accommodate role-based authorization.

Double click on AcountViewModel from the models folder and add a property call Name or RoleName to RegisterViewModel to enable role implementation as shown below
public class RegisterViewModel
    {
        [Display(Name ="User Name")]
        [Required]
        public string Username { get; set; }

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

        [Display(Name ="Role Name")]
        public string RoleName { 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; }
    }
Right click on CsharpnaijaModel.edmx in the models folder to open CsharpnaijaModel.edmx design and update the edmx file to add the created tables for authentication and authorization as shown below

Now double click on AccountCntroller and navigate the Register GET action and add the code snippet below
 [AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.Name = new SelectList(_context.AspNetRoles.ToList(),"Id","Name");
            return View();
        }  

Then add this code await _userManager.AddToRoleAsync(user.Id, model.RoleName); before signIn user in the Register POST Action of AccountController as shown below

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel              model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName =                                model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user,                           model.Password);
                if (result.Succeeded)
                {
                    //Adding user a role
                    await _userManager.AddToRoleAsync(user.Id,                 model.RoleName);

                    await SignInManager.SignInAsync(user,                                  isPersistent:false, rememberBrowser:false);

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

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

Now double click on the Register View in the Account folder of View folder as shown below

Add the view code (html) snippet for users to select user role when registering in the application as shown below
<div class="form-group">
        @Html.LabelFor(m => m.RoleName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.RoleName,(IEnumerable<SelectListItem>)ViewBag.Name, new { @class="form-control"})
        </div>
    </div>

Now the Register View will look like the image below in the browser

The whole Register View code snippet is shown below

@model Csharpnaija_Security.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.RoleName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.RoleName,(IEnumerable<SelectListItem>)ViewBag.Name, new { @class="form-control"})
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}



Let us now implement Authorization on Employee Controller

Double click on Employee Controller from the Controllers folder as shown below

Add Roles=(“Admin”) to the attribute Authorize before the controller class as shown below

[Authorize(Roles ="Admin")]
    public class EmployeesController : Controller
    {}

This means only users with an Admin role can view or access this controller
Now run the application and try accessing the Employee menu without registering or admin role and you a see a login page telling you to login or register as shown below


Congrat, we have successfully implemented Role-based authentication and Authorization

Comments

  1. So good indeed! Glad to have found your page!! This is such great work!! Interesting to read. 토토사이트

    ReplyDelete

Post a Comment

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...