Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Claims based authorization in asp.net core

Suggested Videos
Part 91 - Manage user roles in asp.net core identity | Text | Slides
Part 92 - Model binding not working on submitting razor view with foreach loop | Text | Slides
Part 93 - Manage user claims in asp.net core | Text | Slides

Introduction

In this video we will discuss Claims based authorization i.e using claims to make access control decisions.

Let's say we have the following 3 claims in our application. 
  1. Create Role
  2. Edit Role
  3. Delete Role

To be able to DELETE a ROLE, the logged-in user must have Delete Role claim, otherwise access should be denied.

Implementing Claims based authorization 

There are 2 simple steps to implement Claims based authorization in asp.net core.

  1. Create a claims policy
  2. Use the policy on a controller or a controller action

Creating Claims Policy

Claims are policy based. We create a policy and include one or more claims in that policy. We then need to register the policy. Creating and registering a claims policy is typically done in one step in ConfigureServices() method of the Startup class.

services.AddAuthorization(options =>
{
    options.AddPolicy("DeleteRolePolicy"
        policy => policy.RequireClaim("Delete Role"));
});
  • The options parameter type is AuthorizationOptions
  • Use AddPolicy() method to create the policy
  • The first parameter is the name of the policy and the second parameter is the policy itself
  • To satisfy this policy requirements, the logged-in user must have Delete Role claim
Using Claims Policy for Authorization Checks

The policy can then be used on a controller or a controller action.

[HttpPost]
[Authorize(Policy = "DeleteRolePolicy")]
public async Task<IActionResult> DeleteRole(string id)
{
    // Delete Role
}

To be able to access DeleteRole action, the loggedin user must have Delete Role claim.

Adding Multiple Claims to Policy

To add multiple claims to a given policy, chain RequireClaim() method

services.AddAuthorization(options =>
{
    options.AddPolicy("DeleteRolePolicy"
        policy => policy.RequireClaim("Delete Role")
                        .RequireClaim("Create Role")
                    
        );
});

To satisfy this policy requirements, the loggedin user must have both the claims

asp.net core tutorial for beginners

2 comments:

  1. Dear Sir,
    claim/Role based authorization not reflecting immediately,how can i Update Claims/Roles Identity Value without logging out and back in

    ReplyDelete
  2. Sir if we have more then 20 claims, then we will need to create more then 20 polices, because each claim is using for different-different metods or may be in different controllers ????.

    ReplyDelete

It would be great if you can help share these free resources