Anto Subash.

Published on

Authorization in dotnet core with ABP. Part 3

Table of contents

Intro

In this post we are going to setup the authorization for the dotnet core ABP app. ABP extends ASP.NET Core Authorization by adding permissions as auto policies.

Creating permission

In the ABP application the permission are available in the Contracts project. Find the Permissions class and add your custom permission.

1public static class Todo
2{
3    public const string Default = GroupName + ".Todo";
4    public const string Create = Default + ".Create";
5    public const string Update = Default + ".Update";
6    public const string Delete = Default + ".Delete";
7}

Define permission

PermissionDefinitionProvider is where you have to define the permissions.

1var myGroup = context.AddGroup(TodosPermissions.GroupName);
2
3var todoPermission = myGroup.AddPermission(TodosPermissions.Todo.Default, L("Permission:Default"));
4todoPermission.AddChild(TodosPermissions.Todo.Create, L("Permission:Create"));
5todoPermission.AddChild(TodosPermissions.Todo.Update, L("Permission:Update"));
6todoPermission.AddChild(TodosPermissions.Todo.Delete, L("Permission:Delete"));

Protecting api endpoint based on permission

Once the permission is defined now we can create use the Authorize attribute to enforce the permission

1[Authorize(TodosPermissions.Todo.Default)]
2public async Task<List<TodoDto>> GetAll()
3{
4    return ObjectMapper.Map<List<Todo>, List<TodoDto>>(await todoRepository.GetListAsync());
5}

In the above code we have added the default permission to the getAll api call.

Checking permission

ASP.NET Core provides the IAuthorizationService that can be used to check for authorization. Once you inject, you can use it in your code to conditionally control the authorization.

1var result = await AuthorizationService
2    .AuthorizeAsync(TodosPermissions.Todo.Default);
3if (result.Succeeded == false)
4{
5    //throw exception
6    throw new AbpAuthorizationException("...");
7}

or

1await AuthorizationService.CheckAsync(TodosPermissions.Todo.Default);

For more info check the official docs : https://docs.abp.io/en/abp/latest/Authorization