How to implement Permission Based Access Control with Asp.Net Core

adem caglin :

I am trying to implement permission based access control with aspnet core. For dynamically managing user roles and permissions(create_product, delete_product etc.), they are stored in the database. Data Model is like http://i.stack.imgur.com/CHMPE.png

Before aspnet core (in MVC 5) i was using custom AuthorizeAttribute like below to handle the issue:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string _permissionName { get; set; }
    [Inject]
    public IAccessControlService _accessControlService { get; set; }

    public CustomAuthorizeAttribute(string permissionName = "")
    {
        _permissionName = permissionName;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        var user = _accessControlService.GetUser();
        if (PermissionName != "" && !user.HasPermission(_permissionName))
        {
            // set error result
            filterContext.HttpContext.Response.StatusCode = 403;
            return;
        }
        filterContext.HttpContext.Items["CUSTOM_USER"] = user;
    }
}

Then i was using it in action method like below:

[HttpGet]
[CustomAuthorize(PermissionEnum.PERSON_LIST)]
public ActionResult Index(PersonListQuery query){ }

Additionally, i was using HttpContext.Items["CUSTOM_USER"] in views to show or hide html part:

@if (CurrentUser.HasPermission("<Permission Name>"))
{

}

When i decided to switch aspnet core, all my plan was failed. Because there was no virtual OnAuthorization method in the AuthorizeAttribute. I tried some ways to solve problem. Those are below:

  • Using new policy based authorization(i think it is not suitable for my scenerio)

  • Using custom AuthorizeAttribute and AuthorizationFilter(i read this post https://stackoverflow.com/a/35863514/5426333 but i couldn’t change it properly)

  • Using custom middleware(how to get AuthorizeAttribute of current action?)

  • Using ActionFilter(is it correct for security purpose?)

I couldn’t decide which way is the best for my scenerio and how to implement it.

First question: Is MVC5 implementation bad practice?

Second question: Do you have any suggest to implement aspnet core?

Tseng :

Based on the comments, here an example on how to use the policy based authorization:

public class PermissionRequirement : IAuthorizationRequirement
{
    public PermissionRequirement(PermissionEnum permission)
    {
         Permission = permission;
    }

    public PermissionEnum Permission { get; }
}

public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
    private readonly IUserPermissionsRepository permissionRepository;

    public PermissionHandler(IUserPermissionsRepository permissionRepository)
    {
        if(permissionRepository == null)
            throw new ArgumentNullException(nameof(permissionRepository));

        this.permissionRepository = permissionRepository;
    }

    protected override void Handle(AuthorizationContext context, PermissionRequirement requirement)
    {
        if(context.User == null)
        {
            // no user authorizedd. Alternatively call context.Fail() to ensure a failure 
            // as another handler for this requirement may succeed
            return null;
        }

        bool hasPermission = permissionRepository.CheckPermissionForUser(context.User, requirement.Permission);
        if (hasPermission)
        {
            context.Succeed(requirement);
        }
    }
}

And register it in your Startup class:

services.AddAuthorization(options =>
{
    UserDbContext context = ...;
    foreach(var permission in context.Permissions) 
    {
        // assuming .Permission is enum
        options.AddPolicy(permission.Permission.ToString(),
            policy => policy.Requirements.Add(new PermissionRequirement(permission.Permission)));
    }
});

// Register it as scope, because it uses Repository that probably uses dbcontext
services.AddScope<IAuthorizationHandler, PermissionHandler>();

And finally in the controller

[HttpGet]
[Authorize(Policy = PermissionEnum.PERSON_LIST.ToString())]
public ActionResult Index(PersonListQuery query)
{
    ...
}

The advantage of this solution is that you can also have multiple handlers for a requirement, i.e. if first one succeed the second handler can determine it's a fail and you can use it with resource based authorization with little extra effort.

The policy based approach is the preferred way to do it by the ASP.NET Core team.

From blowdart:

We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead you should be writing authorization requirements.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to implement Permission Based Access Control with Asp.Net Core

分類Dev

How to implement permission based authorization in ASP.net core Identity?

分類Dev

React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

分類Dev

Use ADFS-based authentication inside ASP.NET Core to access a SQL Server using Windows authentication?

分類Dev

How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?

分類Dev

How best to implement Google social sign-in authentication in ASP.NET Core?

分類Dev

How to I access the DbContext of EF core from another project when used in ASP.NET core?

分類Dev

How to implement Custom Model Validator in .NET Core

分類Dev

Implement Pagination in ASP.NET Core 2.1 Web API

分類Dev

How to order selected data based on nested table in ASP.NET CORE Code first

分類Dev

How to query a column in a database based on specific value MVC ASP.NET Core

分類Dev

How to access deeply nested array with MongoDB (ASP.NET Core 2.2)

分類Dev

show month in asp.net calendar control based on value of dropdownlist

分類Dev

ASP.NET Core CORS WebAPI:Access-Control-Allow-Originヘッダーを保持しません

分類Dev

Domain-based routing in ASP.NET Core 2.0

分類Dev

Path based authentication in ASP.NET Core MVC 2.0

分類Dev

Role based authorization in ASP.NET Core 3.1 with Identity and ExternalLogin

分類Dev

Can't access method (Azure Tables with ASP.NET Core)

分類Dev

How to enable CORS in ASP.NET Core

分類Dev

In ASP.NET Core 2.1 how do I add menu items after the user has logged in based on Role?

分類Dev

How to implement A/B split testing in ASP.NET?

分類Dev

How to implement ViewModels for asp.net MVC 5?

分類Dev

VueJS router guards to implement access control mechanism

分類Dev

how to count value of last column in repeater control in asp.net

分類Dev

ASP.NET Core on .NET 4.6 - how to do https

分類Dev

Store does not implement IUserRoleStore<TUser> ASP.NET Core 2.1 Identity

分類Dev

ASP.NET 5:応答でのAccess-Control-Allow-Origin

分類Dev

AddCors not showing any headers for Access-Control-Allow-Origin ASP.NET

分類Dev

Access/Modify master page's control in other pages - Asp.net

Related 関連記事

  1. 1

    How to implement Permission Based Access Control with Asp.Net Core

  2. 2

    How to implement permission based authorization in ASP.net core Identity?

  3. 3

    React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

  4. 4

    Use ADFS-based authentication inside ASP.NET Core to access a SQL Server using Windows authentication?

  5. 5

    How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?

  6. 6

    How best to implement Google social sign-in authentication in ASP.NET Core?

  7. 7

    How to I access the DbContext of EF core from another project when used in ASP.NET core?

  8. 8

    How to implement Custom Model Validator in .NET Core

  9. 9

    Implement Pagination in ASP.NET Core 2.1 Web API

  10. 10

    How to order selected data based on nested table in ASP.NET CORE Code first

  11. 11

    How to query a column in a database based on specific value MVC ASP.NET Core

  12. 12

    How to access deeply nested array with MongoDB (ASP.NET Core 2.2)

  13. 13

    show month in asp.net calendar control based on value of dropdownlist

  14. 14

    ASP.NET Core CORS WebAPI:Access-Control-Allow-Originヘッダーを保持しません

  15. 15

    Domain-based routing in ASP.NET Core 2.0

  16. 16

    Path based authentication in ASP.NET Core MVC 2.0

  17. 17

    Role based authorization in ASP.NET Core 3.1 with Identity and ExternalLogin

  18. 18

    Can't access method (Azure Tables with ASP.NET Core)

  19. 19

    How to enable CORS in ASP.NET Core

  20. 20

    In ASP.NET Core 2.1 how do I add menu items after the user has logged in based on Role?

  21. 21

    How to implement A/B split testing in ASP.NET?

  22. 22

    How to implement ViewModels for asp.net MVC 5?

  23. 23

    VueJS router guards to implement access control mechanism

  24. 24

    how to count value of last column in repeater control in asp.net

  25. 25

    ASP.NET Core on .NET 4.6 - how to do https

  26. 26

    Store does not implement IUserRoleStore<TUser> ASP.NET Core 2.1 Identity

  27. 27

    ASP.NET 5:応答でのAccess-Control-Allow-Origin

  28. 28

    AddCors not showing any headers for Access-Control-Allow-Origin ASP.NET

  29. 29

    Access/Modify master page's control in other pages - Asp.net

ホットタグ

アーカイブ