Role Based Authorization in ASP.NET Core Application

Vivek Jaiswal
1928
{{e.like}}
{{e.dislike}}
1 years

Watch Video  Download Code 

In this article, I will discuss How to perform Role based Authorization in ASP.NET Core application.

Role based authorization checks are declarative, the programmer can embeds them with in their code, against a controller or action. This specify the user roles that current user is authorize to access the requested resource.

ASP.NET Core Identity is membership program, which allow user to add authentication and authorization functionality to the web application. User can access the system on behalf of their roles/claims. Using Authorization, each authenticated users have limited access to the web application.

For example, the following code limit the access of user on controller level, means users with Admin role have rights to access this controller.

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

  }

You can also specify multiple Roles as a comma separated list.

  [Authorize(Roles ="Inventory,Finance")]
  public class HomeController : Controller
  {
  }

This controller would be only accessible for users with Inventory role or Finance role.

You can also apply multiple attributes then an accessing user must be a member of all specified roles.

In following code sample user must be member of both Inventory and Finance role

[Authorize(Roles = " Inventory")]
[Authorize(Roles = " Finance")]
public class HomeController : Controller
{

}

You can also limit the user by applying role authorization attribute on the action level.

  [Authorize(Roles ="Admin,User")]
 public IActionResult Index()
 {
   return View();
 }

This action method is accessible for both users with Admin or User role.

Now follow the below steps for performing Role based Authorization in ASP.NET Core applicaton.

Step1:  First off, let’s create an ASP.NET Core MVC project in Visual Studio.

Open Visual Studio 2017 》New 》 ASP.NET Core Web Application 》 MVC

 

Step2: Add Controller to the application: Right click on controller folder and add controller class as AccountController.cs , here we will write business logic for performing Role based Authorization.

Now write the following code snippet inside AccountController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
namespace RoleBasedAuth.Controllers
{
    public class AccountController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Login(string username,string password)
        {
            if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
            {
                return RedirectToAction("Login");
            }
            ClaimsIdentity identity = null;
            bool isAuthenticate = false;
            if (username=="admin" && password=="a")
            {
                identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name,username),
                    new Claim(ClaimTypes.Role,"Admin")
                }, CookieAuthenticationDefaults.AuthenticationScheme);
                isAuthenticate = true;
            }
            if (username == "demo" && password == "c")
            {
                identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name,username),
                    new Claim(ClaimTypes.Role,"User")
                }, CookieAuthenticationDefaults.AuthenticationScheme);
                isAuthenticate = true;
            }
            if (isAuthenticate)
            {
                var principal = new ClaimsPrincipal(identity);
                var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
    }
}

In the above code, I have used ClaimsIdentity, which contain the property Claims like Name and Role.  Here I have created two account one for Admin and other one for User. Here ClaimsPrincipal has the identities property which return the collection of ClaimsIdentity. That means a User can have multiple identities.

If Authentication is successful then create object for ClaimsPrincipal and then redirect user to Index page inside the HomeController.

Add Views to the Application:

To add Views for controller class, we need to create folder inside Views folder with same name as Controller class (Here name as Account) and then add Views to that folder.

To add Views file, Right click on Account folder inside Views folder and then select View name as Login.cshtml.

Now write the following code snippet inside to the Login.cshtml

<div class="container">
    <div class="row">
        <div class="col-md-3">
            <h3>Login</h3>
            <form asp-action="Login" method="post">
                <div class="form-group">
                    <label>UserName</label>
                    <input type="text" class="form-control" id="username" name="username" />
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" id="password" name="password" />
                </div>
                <div class="form-group">
                    <label></label>
                    <input type="submit" class="btn btn-primary" value="Login" />
                </div>
            </form>
        </div>
    </div>
</div>

In the above code I have created Views for Login page where user can enter their credential for accessing the resource.

Now go to the ConfigureServices()  method of the Startup class in Statup.cs

Add following CookiePolicyOptions and AuthenticationScheme.

services.Configure<CookiePolicyOptions>(options =>
{
  options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

 

ConfigureServices() method look like this:

public void ConfigureServices(IServiceCollection services)
  {
      services.Configure<CookiePolicyOptions>(options =>
      {
          options.MinimumSameSitePolicy = SameSiteMode.None;
      });  
     services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
   }

SameSite is an IETF draft standard designed to provide some protection against cross-site request forgery (CSRF) attacks. SameSiteMode.None must be used to allow cross-site cookie use.

AuthenticationScheme passed to AddAuthentication sets the default authentication scheme for the app. AuthenticationScheme is useful when there are multiple instances of cookie authentication and you want to authorize with a specific scheme.

Now go to the Configure method into the Startup class and add CookiePolicy and Authentication.

app.UseCookiePolicy();
app.UseAuthentication();

Configure look like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Now limit the access of Action into to Controller Class (Here HomeController) according the user roles.

  [Authorize(Roles ="Admin,User")]
  public IActionResult Index()
  {
      return View();
  }
  [Authorize(Roles = "User")]
  public IActionResult About()
  {
      ViewData["Message"] = "Your application description page.";
   
      return View();
  }

In the above code I have limit the access of Index for Users with Admin or User role and About action for User role only.

Now run the application.

 

Thanks.

If you like this article, share with you friends.

{{e.like}}
{{e.dislike}}
Comments
Follow up comments
{{e.Name}}
{{e.Comments}}
{{e.days}}
Follow up comments
{{r.Name}}
{{r.Comments}}
{{r.days}}