Policy-Based Authorization in .NET Core With Example

In this article, we will learn Policy-Based Authorization in .NET Core With Example. We will implement this authorization in .NET Core application. There are many ways to apply authorization in .NET Core, however, in this article, we will focus on Policy-based authorization. So let’s start.

Overview of Authorization in Web Applications

The process of determining whether a user has permission to access a resource or carry out a particular action is known as authorization in web applications. It is an important part of application security because it makes sure that only authorized users can access certain data or do certain transactions.

Importance of Secure Authorization in .NET Core

In ASP.NET Core, authorization is an essential security mechanism for controlling access and safeguarding sensitive data and functionality. Based on the requirements of their application, developers can select from a variety of authorization policies and authentication methods.

What Do You Mean by Policy-Based Authorization in .NET Core?

The policy-based approach defines policies that allow users who access a particular resource. In . NET Core, a developer can use the [Authorize(Policy = "PolicyName")] attribute to restrict access defined in the policy. We can use the Policy attribute over the controller as well. In the next section of this article, we will see how to implement this policy in .NET based project.

Why do we need policy-based authorization in .NET Core?

Policy-based authorization in .NET allows us to write custom logic for authorization for our application and this makes our application more secure.

Apart from this, this mechanism allows the re-usability features. It means we define the policy in one place and we can apply this anywhere in the current application. So, in this way, Policy-based authorization provides us with a better and more controlled way to apply security access to the application.

How to Implement Policy-Based Authorization in .NET Core

In this section of the article, we will create the .NET Core MVC project and will implement Policy-Based Authorization. You may use the existing .NET Core MVC Project if you have one.

To implement Policy-Based Authorization in .NET Core MVC Project, ensure we have the following:

  • .NET SDK installed (.NET 7 or .NET 8)
  • .NET Core MVC Project (If you want to know how to create .NET MVC Project in Visual Studio, Please Click Here.)

So, let’s follow the below steps to apply Policy-Based Authorization in .NET Core:

Install Required Packages

Once we are ready with .NET Core MVC Project, we will install the following packages from NuGet Package Manager:

dotnet add package Microsoft.AspNetCore.Authentication
dotnet add package Microsoft.AspNetCore.Authorization

Register Authorization Policy

Let’s define the Authorization policy in the Program.cs file. We can define one or more policies here:

services.AddAuthorization(options =>
{
    options.AddPolicy("Admin", policy =>
        policy.RequireRole("Admin")); 
});

Apply Authorization Policy on .NET MVC Controller

Here we will use the [Authorize] attribute to apply authorization on a controller and this will apply the policy on each action method within this controller.

[Authorize(Policy = "Admin")]

In the code snippet, we are applying a policy and the policy name is Admin. We can apply a different authorization policy on each action method in a controller.

Add Authentication and User Claims

To make sure authentication is set up in order to apply the required claims and roles.

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie(options =>
           {
               options.LoginPath = "/Account/Login";
               options.AccessDeniedPath = "/Account/AccessDenied";
           });

Authentication Mechanism for Identity Claim

To issue the claim we will apply an authentication mechanism on the Login action.

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public IActionResult Login(LoginViewModel model)
        {

            if (ModelState.IsValid)
            {
                if (model != null)
                {
                    if (model.UserName == "admin" && model.Password == "Admin123" && model.Type == "auth")
                    {
                        var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Role, "Admin") // Add the role claim
            };

                        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        var authProperties = new AuthenticationProperties
                        {
                            // Optionally set other authentication properties here
                        };

                         HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                            new ClaimsPrincipal(claimsIdentity),
                            authProperties);
                        return RedirectToAction("Index", "Admin");
                    }
                    // Login successful - Implement user session management (e.g., using cookies)
                    //return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid username or password.");
                }
            }

            // Login failed - Redisplay login view
            return View(model);
        }

Remove or Clear the Identity

To remove the claims and clear the authorization policy we will use the Logout mechanism.

Logout View Code Snippet:

 @if (User.Identity.IsAuthenticated)
 {

     <li class="nav-item">
         <form asp-controller="Account" asp-action="Logout" method="post" class="form-inline">
             <button type="submit" class="btn btn-link nav-link">Logout</button>
         </form>
     </li>
 }

Clear the Cookie on Signout:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Index", "Home");
}

How does policy-based authorization differ from claim-based authorization?

In .NET Core, Policy-based and Claim-based authorization have their own security mechanism. However, we can combine both the authorization process in a single project. So, let’s see a couple of differences between policy-based authorization and claim-based authorization.

Policy-Based Authorization

  • It is a flexible approach where we can define the policies and encapsulate the authorization mechanism.
  • Policy-based authorisation allows us to add one or more than one policy such as a Policy for the Admin Role, a Policy for the User Role, a Policy for the Moderator Role etc.

How to Define Policy

services.AddAuthorization(options =>
{
    options.AddPolicy("Admin", policy =>
        policy.RequireRole("Admin")); 
});

Here, the code adds the authorization to the dependency injection container. Next, we define the policy with the name “Admin” and the policy requires the “Admin” role to apply authorization policy.

Claim-Based Authorization

  • Claim-based handles the data in a key-value pair. It contains the roles, and permissions of the user as attributes.
  • It looks for the claim in the authenticated user’s identity for further authorizing the user.

How to Define Claim-Based Authorization

builder.Services.AddAuthorization(options =>
{
   options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("PermanentEmployee"));
});

Here, we force the application to enable the authorization process. We define the policy name as “EmployeeOnly”. So, the policy EmployeeOnly only authorizes those users who have a claim attribute as “Permanent”.

Can We Combine Claim-Based and Policy-Based Authorization?

Can We Combine Claim-Based and Policy-Based Authorization in a Single .NET Core Application?

Yes, we can combine Claim-Based and Policy-Based Authorization in a single .NET Core application. Let’s see the implementation in .NET Core:

Let’s define a policy that requires the user to have a claim attribute as “AccountDepartment”

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("EmployeeOnly", policy =>
        policy.RequireClaim("AccountDepartment"));
});

Define another policy that requires the user’s role as admin

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin"));
});

Apply Claim-Based and Policy-Based Authorization both:

To apply the authorization, we use [Authorize] attribute:

[Authorize(Policy = "AccountDepartment")]
public IActionResult GetEmployeeBonus()
{
    return View();
}

[Authorize(Policy = "AdminOnly")]
public IActionResult AdminDashboard()
{
    return View();
}

Conclusion

In this article, we focused on Policy-Based authorization in .NET Core. We learned policy-based authorisation and how to implement it in a .NET core-based application. In addition to this, we also covered claim-based authorization and compared it with policy-based approval.

Hope you like this article on Policy-Based authorization in .NET Core. If this is helpful to you, please share this article with your tech group.

Keep Following: SharePointCafe.NET

Leave a Comment

RSS
YouTube
YouTube
Instagram