Basic Role-based Authorization in Asp.Net Core 2019

Previous articles :- https://sagarjaybhay.com/asp-net-core/

Role-based Authorization

Authorization means that if the user has rights he will able to see things. For this we use simple Authorize attribute in this we know that when we use simple Authorize attribute like below

[HttpGet]
        [Authorize]
        public ViewResult Edit(int id)
        {
            try
            {
                Student st = _repository.GetStudents(id);
                StudentEditViewModelClass editViewModelClass=new StudentEditViewModelClass()
                {
                    ExistingPhotoPath = st.PhotoPath,
                    Address = st.Address,
                    Division = st.Division,
                     FullName = st.FullName,
                     Id = id
                };
                return View(editViewModelClass);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }

It will only check the user is login or not which is simple.

In this, we understand Role-based authorization means what,

Suppose we have 2 users ABC and xyz and ABC have administrator rights and xyz have general rights so if you want some controller only accessed by the administrator you can do so by doing the following attribute with value.

[HttpGet]
        [Authorize(Roles = "Admin")]
        public ViewResult Edit(int id)
        {
            try
            {
                Student st = _repository.GetStudents(id);
                StudentEditViewModelClass editViewModelClass=new StudentEditViewModelClass()
                {
                    ExistingPhotoPath = st.PhotoPath,
                    Address = st.Address,
                    Division = st.Division,
                     FullName = st.FullName,
                     Id = id
                };
                return View(editViewModelClass);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }

In above code  we mark method with [Authorize(Roles = “Admin”)]

 This attribute you can use with a controller in the same way. Now you can give multiple values to Authorize attribute like below [Authorize(Roles = “Admin, User”)]

This also works the same way and has access to multiple roles like admin and user.

Suppose you have created a user and which is not having any kind of role assign to it then asp redirects this user to log in when it going to access the particular method or controller another action which is marked with this attribute.

[Authorize(Roles = "Admin,User")]
    public class HomeController : Controller
    {
        private IStudentRepository _repository;
        private IHostingEnvironment histingEnviroment;
        public ILogger loggerObject { get; set; }
        public HomeController(IStudentRepository repository,IHostingEnvironment ihostEnvironment,ILogger<HomeController> logger)
        {
            this._repository = repository;
            this.histingEnviroment = ihostEnvironment;
            loggerObject = logger;
        }

        //[Route("")]
        //[Route("~/")]
        //[Route("[action]")]
        [Authorize(Roles = "User")]
        public ViewResult Index()
        {

            loggerObject.LogCritical("LogCritical");
            loggerObject.LogDebug("LogDebug");
            loggerObject.LogError("LogError");
            loggerObject.LogInformation("LogInformation");
            loggerObject.LogTrace("LogTrace");
            loggerObject.LogWarning("LogWarning");

            var v = _repository.GetAllStudent();
            return View(v);
        }

       // [Route("[action]")]
       [AllowAnonymous]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
}

Role-based Authorization
Authorize Role In Asp.Net Core

How to hide and unhide menuItem in asp.net core based on roles?

When you want to achieve this functionality you need to use SignInManager class with IsSignedIn Method and for role-based, we need to use IsInRole method of User object like below in _Layout.cshtml file.

   @if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
                    {
                        <li class="nav-item">
                            <a asp-action="CreateRoles" asp-controller="Rolemanag" class="nav-link">Create Roles</a>
                        </li>
                        <li class="nav-item">
                            <a asp-action="ListOfRoles" asp-controller="Rolemanag" class="nav-link">Role List</a>
                        </li>
                    }

How to add access denied call in asp.net core?

In this the controller which causing you issue or generally account controller where authentication and authorization start is the start point of application so add AccessDenied method in that controller like below.

[HttpGet]
        [AllowAnonymous]
        public IActionResult AccessDenied()
        {
            return View();
        }

Make sure that the method has AllowAnonymous attribute and should respond to get a call.

Html of this method is like below

@{
    ViewData["Title"] = "AccessDenied";
}

<h1>AccessDenied</h1>

<div class="text-center">
    <h1><div class="text-danger">Access Denied</div></h1>
    <div class="text-danger">You don't have permission to access this page.</div>
    <div class="img-fluid">
        <img src="images/access.png"/>
    </div>
</div>

The out put of this Method is like below

access denied in asp.net core
access denied in asp.net core

How to display all users from the identity database?

Create a ListOfUser action method in a controller in our RoleManagerController. Register users are stored in the asp.net core identity database in the AspNetUsers tables.

To retrieve the users from the database we need UserManager service and this service we already injected in our controller.

users in asp.net core
users in asp.net core

[HttpGet]
        public IActionResult ListOfUsers()
        {
            var users = _userManager.Users;
            return View(users);

        }

This is our method in RoleManager controller and from this, we can get the users list. Then we pass this user list to our view.

@model IEnumerable<ExtendedIdentityUser>

@{
    ViewData["Title"] = "List Of Users";
}

<h1>List Of Users</h1>


@if (Model.Any())
{


    foreach (var users in Model)
    {
        
        <div class="card">
        
            <div class="card-header">
                <div class="row">
                    <div class="col-2"> User ID</div>
                    <div class="col-8"> @users.Id</div>
                </div>
            </div>
        
            <div class="card-body">
                <div class="row">
                    <div class="col-2">Email ID</div>
                    <div class="col-8"> @users.Email</div>
                </div>

            </div>
        
            <div class="card-footer">
                <button type="submit" class="btn btn-primary"> Edit </button>
                <button type="submit" class="btn btn-primary"> Cancel </button>
            </div>
        </div>
        
    }
}
else
{
    <h1>No User Is Present Right Now.</h1>
}

By passing the user’s list to our view we get the below output.

List of users in asp.net core
List of users in asp.net core

In this output, we show only userid and Email Id not the rest of the information. But if we want to display this information we can get easily. See below screenshot as we pass users list to view we are able to access the properties of that class.

List of users intellisense in asp.net core
List of users intellisense in asp.net core

GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts