developer tip

웹 MVC 애플리케이션에서 액세스 제어 목록을 어떻게 구현할 수 있습니까?

optionbox 2020. 8. 28. 07:20
반응형

웹 MVC 애플리케이션에서 액세스 제어 목록을 어떻게 구현할 수 있습니까?


첫 번째 질문

MVC에서 가장 간단한 ACL을 구현하는 방법을 설명해 주시겠습니까?

다음은 Controller에서 Acl을 사용하는 첫 번째 방법입니다.

<?php
class MyController extends Controller {

  public function myMethod() {        
    //It is just abstract code
    $acl = new Acl();
    $acl->setController('MyController');
    $acl->setMethod('myMethod');
    $acl->getRole();
    if (!$acl->allowed()) die("You're not allowed to do it!");
    ...    
  }

}
?>

이것은 매우 나쁜 접근 방식이며 마이너스는 Acl 코드를 각 컨트롤러의 메서드에 추가해야하지만 추가 종속성이 필요하지 않습니다!

다음 접근 방식은 모든 컨트롤러의 메서드를 만들고 컨트롤러의 메서드 private에 ACL 코드를 추가 __call하는 것입니다.

<?php
class MyController extends Controller {

  private function myMethod() {
    ...
  }

  public function __call($name, $params) {
    //It is just abstract code
    $acl = new Acl();
    $acl->setController(__CLASS__);
    $acl->setMethod($name);
    $acl->getRole();
    if (!$acl->allowed()) die("You're not allowed to do it!");
    ...   
  }

}
?>

이전 코드보다 낫지 만 주요 단점은 ...

  • 모든 컨트롤러의 메서드는 비공개 여야합니다.
  • 각 컨트롤러의 __call 메서드에 ACL 코드를 추가해야합니다.

다음 접근법은 Acl 코드를 부모 컨트롤러에 넣는 것이지만 여전히 모든 자식 컨트롤러의 메서드를 비공개로 유지해야합니다.

해결책은 무엇인가? 그리고 모범 사례는 무엇입니까? 메서드 실행을 허용할지 여부를 결정하기 위해 Acl 함수를 어디에서 호출해야합니까?

두 번째 질문

두 번째 질문은 Acl을 사용하여 역할을 얻는 것입니다. 손님, 사용자 및 사용자의 친구가 있다고 가정 해 봅시다. 사용자는 친구 만 볼 수있는 프로필보기에 대한 액세스를 제한했습니다. 모든 참석자는이 사용자의 프로필을 볼 수 없습니다. 그래서 여기에 논리가 있습니다 ..

  • 호출되는 메서드가 프로필인지 확인해야합니다.
  • 이 프로필의 소유자를 감지해야합니다.
  • 시청자가이 프로필의 소유자인지 아닌지 확인해야합니다.
  • 이 프로필에 대한 제한 규칙을 읽어야합니다.
  • 프로파일 메소드 실행 여부를 결정해야합니다

주요 질문은 프로필 소유자를 감지하는 것입니다. 우리는 모델의 $ model-> getOwner () 메소드를 실행하는 것만으로 프로필의 소유자를 감지 할 수 있지만 Acl은 모델에 대한 액세스 권한이 없습니다. 이것을 어떻게 구현할 수 있습니까?

내 생각이 분명하기를 바랍니다. 내 영어에 대해 죄송합니다.

감사합니다.


첫 번째 부분 / 답변 (ACL 구현)

내 겸손한 의견으로는, 이것에 접근하는 가장 좋은 방법은 데코레이터 패턴 을 사용하는 것 입니다 . 기본적으로 이것은 당신이 당신의 물건을 가져다 다른 물건 안에 놓아 두는 것을 의미합니다 . 이것은 보호 껍질처럼 행동 할 것입니다. 이것은 원래 클래스를 확장 할 필요가 없습니다. 다음은 예입니다.

class SecureContainer
{

    protected $target = null;
    protected $acl = null;

    public function __construct( $target, $acl )
    {
        $this->target = $target;
        $this->acl = $acl;
    }

    public function __call( $method, $arguments )
    {
        if ( 
             method_exists( $this->target, $method )
          && $this->acl->isAllowed( get_class($this->target), $method )
        ){
            return call_user_func_array( 
                array( $this->target, $method ),
                $arguments
            );
        }
    }

}

그리고 이것은 이러한 종류의 구조를 사용하는 방법입니다.

// assuming that you have two objects already: $currentUser and $controller
$acl = new AccessControlList( $currentUser );

$controller = new SecureContainer( $controller, $acl );
// you can execute all the methods you had in previous controller 
// only now they will be checked against ACL
$controller->actionIndex();

아시다시피이 솔루션에는 몇 가지 장점이 있습니다.

  1. 봉쇄는 인스턴스뿐만 아니라 모든 개체에 사용할 수 있습니다. Controller
  2. check for authorization happens outside the target object, which means that:
    • original object is not responsible for access control, adheres to SRP
    • when you get "permission denied", you are not locked inside a controller, more options
  3. you can inject this secured instance in any other object, it will retain the protection
  4. wrap it & forget it .. you can pretend that it is the original object, it will react the same

But, there are one major issue with this method too - you cannot natively check if secured object implements and interface ( which also applies for looking up existing methods ) or is part of some inheritance chain.

Second part/answer (RBAC for objects)

In this case the main difference you should recognize is that you Domain Objects (in example: Profile) itself contains details about owner. This means, that for you to check, if (and at which level) user has access to it, it will require you to change this line:

$this->acl->isAllowed( get_class($this->target), $method )

Essentially you have two options:

  • Provide the ACL with the object in question. But you have to be careful not to violate Law of Demeter:

    $this->acl->isAllowed( get_class($this->target), $method )
    
  • Request all the relevant details and provide the ACL only with what it needs, which will also make it a bit more unit-testing friendly:

    $command = array( get_class($this->target), $method );
    /* -- snip -- */
    $this->acl->isAllowed( $this->target->getPermissions(), $command )
    

Couple videos that might help you to come up with your own implementation:

Side notes

You seem to have the quite common ( and completely wrong ) understanding of what Model in MVC is. Model is not a class. If you have class named FooBarModel or something that inherits AbstractModel then you are doing it wrong.

In proper MVC the Model is a layer, which contains a lot of classes. Large part of the classes can be separated in two groups , based on the responsibility:

- Domain Business Logic

(read more: here and here):

Instances from this group of classes deal with computation of values, check for different conditions, implement sales rules and do all the rest what you would call "business logic". They have no clue how data is stored, where it is stored or even if storage exists in first place.

Domain Business object do not depend on database. When you are creating an invoice, it does not matter where data comes from. It can be either from SQL or from a remote REST API, or even screenshot of a MSWord document. The business logic does no change.

- Data Access and Storage

Instances made from this group of classes are sometimes called Data Access Objects. Usually structures that implement Data Mapper pattern ( do not confuse with ORMs of same name .. no relation ). This is where your SQL statements would be (or maybe your DomDocument, because you store it in XML).

Beside the two major parts, there is one more group of instances/classes, that should be mentioned:

- Services

This is where your and 3rd party components come in play. For example, you can think of "authentication" as service, which can be provided by your own, or some external code. Also "mail sender" would be a service, which might knit together some domain object with a PHPMailer or SwiftMailer, or your own mail-sender component.

Another source of services are abstraction on to on domain and data access layers. They are created to simplify the code used by controllers. For example: creating new user account might require to work with several domain objects and mappers. But, by using a service, it will need only one or two lines in the controller.

What you have to remember when making services, is that the whole layer is supposed to be thin. There is no business logic in services. They are only there to juggle domain object, components and mappers.

One of things they all have in common would be that services do not affect the View layer in any direct way, and are autonomous to such an extent, that they can be ( and quit often - are ) used outside the MVC structure itself. Also such self-sustained structures make the migration to a different framework/architecture much easier, because of extremely low coupling between service and the rest of application.


ACL and Controllers

First of all: These are different things / layers most often. As you criticize the exemplary controller code, it puts both together - most obviously too tight.

tereško already outlined a way how you could decouple this more with the decorator pattern.

I'd go one step back first to look for the original problem you're facing and discuss that a bit then.

On the one hand you want to have controllers that just do the work they're commanded to (command or action, let's call it command).

On the other hand you want to be able to put ACL in your application. The field of work of these ACLs should be - if I understood your question right - to control access to certain commands of your applications.

This kind of access control therefore needs something else that brings these two together. Based on the context in which a command is executed in, ACL kicks in and decisions need to be done whether or not a specific command can be executed by a specific subject (e.g. the user).

Let's summarize to this point what we have:

  • Command
  • ACL
  • User

The ACL component is central here: It needs to know at least something about the command (to identify the command to be precise) and it needs to be able to identify the user. Users are normally easily identified by a unique ID. But often in webapplications there are users that are not identified at all, often called guest, anonymous, everybody etc.. For this example we assume that the ACL can consume a user object and encapsulate these details away. The user object is bound to the application request object and the ACL can consume it.

What about identifying a command? Your interpretation of the MVC pattern suggests that a command is compound of a classname and a method name. If we look more closely there are even arguments (parameters) for a command. So it's valid to ask what exactly identifies a command? The classname, the methodname, the number or names of arguments, even the data inside any of the arguments or a mixture of all this?

Depending on which level of detail you need to identify a command in your ACL'ing, this can vary a lot. For the example let's keep it simply and specify that a command is identified by the classname and method name.

So the context of how these three parts (ACL, Command and User) are belonging to each other is now more clear.

We could say, with an imaginary ACL compontent we can already do the following:

$acl->commandAllowedForUser($command, $user);

Just see what is happeninig here: By making both the command and the user identifiable, the ACL can do it's work. The job of the ACL is unrelated to the work of both the user object and the concrete command.

There is only one part missing, this can't live in the air. And it doesn't. So you need to locate the place where the access control needs to kick in. Let's take a look what happens in a standard webapplication:

User -> Browser -> Request (HTTP)
   -> Request (Command) -> Action (Command) -> Response (Command) 
   -> Response(HTTP) -> Browser -> User

To locate that place, we know it must be before the concrete command is executed, so we can reduce that list and only need to look into the following (potential) places:

User -> Browser -> Request (HTTP)
   -> Request (Command)

At some point in your application you know that a specific user has requested to perform a concrete command. You already do some sort of ACL'ing here: If a user requests a command which does not exists, you don't allow that command to execute. So where-ever that happens in your application might be a good place to add the "real" ACL checks:

The command has been located and we can create the identification of it so the ACL can deal with it. In case the command is not allowed for a user, the command will not be executed (action). Maybe a CommandNotAllowedResponse instead of the CommandNotFoundResponse for the case a request could not be resolved onto a concrete command.

The place where the mapping of a concrete HTTPRequest is mapped onto a command is often called Routing. As the Routing already has the job to locate a command, why not extend it to check if the command is actually allowed per ACL? E.g. by extending the Router to a ACL aware router: RouterACL. If your router does not yet know the User, then the Router is not the right place, because for the ACL'ing to work not only the command but also the user must be identified. So this place can vary, but I'm sure you can easily locate the place you need to extend, because it's the place that fullfills the user and command requirement:

User -> Browser -> Request (HTTP)
   -> Request (Command)

User is available since the beginning, Command first with Request(Command).

So instead of putting your ACL checks inside each command's concrete implementation, you place it before it. You don't need any heavy patterns, magic or whatever, the ACL does it's job, the user does it's job and especially the command does it's job: Just the command, nothing else. The command has no interest to know whether or not roles apply to it, if it's guarded somewhere or not.

So just keep things apart that don't belong to each other. Use a slightly rewording of the Single Responsibility Principle (SRP): There should be only one reason to change a command - because the command has changed. Not because you now introduce ACL'ing in your application. Not because you switch the User object. Not because you migrate from an HTTP/HTML interface to a SOAP or command-line interface.

The ACL in your case controls the access to a command, not the command itself.


One possibility is to wrap all your controllers in another class that extends Controller and have it delegate all the function calls to the wrapped instance after checking for authorization.

You could also do it more upstream, in the dispatcher (if your application does indeed have one) and lookup the permissions based on the URLs, instead of control methods.

edit: Whether you need to access a database, a LDAP server, etc. is orthogonal to the question. My point was that you could implement an authorization based on URLs instead of controller methods. These is more robust because you typically won't be changing your URLs (URLs area kind of public interface), but you might as well change the implementations of your controllers.

Typically, you have one or several configuration files where you map specific URL patterns to specific authentication methods and authorization directives. The dispatcher, before dispatching the request to the controllers, determines if the user is authorized and aborts the dispatching if he's not.

참고URL : https://stackoverflow.com/questions/3430181/how-can-i-implement-an-access-control-list-in-my-web-mvc-application

반응형