拒绝访问私人区域Phalcon PHP ACL

I would like to deny access to the private areas on my website. But I don't know what I am doing wrong.

I don't want to use Acl::DENY as the default rule. Instead I am using Acl::ALLOW as the global rule and denying access to the private resources.

Here is my code:

<?php 
use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Resource;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;


class SecurityPlugin extends Plugin {

    public function getAcl() {
        if (!isset($this->persistent->acl)) {

            $acl = new AclList();
            $acl->setDefaultAction(Acl::ALLOW);

            $roles = array(
                'admin' => new Role('Administrators'),
                'guests' => new Role('Guests')
            );
            foreach ($roles as $role) {
                $acl->addRole($role);
            }

            //Private area resources
            $privateResources = array(
                'admin'        => array('index'),
                'products'     => array('index', 'search', 'new');

            foreach ($privateResources as $resource => $actions) {
                $acl->addResource(new Resource($resource), $actions);
            }

            foreach ($privateResources as $resource => $actions) {
                foreach ($actions as $action) {
                    $acl->deny('Guests', $resource, $action);
                }
            }

        }

        return $this->persistent->acl;
    }


    public function beforeDispatch(Event $event, Dispatcher $dispatcher) {

        $auth = $this->session->get('auth');
        if (!$auth) {
            $role = 'Guests';
        } else {
            $role = 'Admin';
        }

        $controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();

        $acl = $this->getAcl();

        $allowed = $acl->isAllowed($role, $controller, $action);
        if ($allowed != Acl::ALLOW) {
            $dispatcher->forward(array(
                'controller' => 'errors',
                'action'     => 'show401'
            ));
            $this->session->destroy();
            return false;
        }
    }
}

Thank you, for trying to help me.

1个回答

You forgot to actually assign your ACL definitions to $this->persistent->acl

public function getAcl() {
    if (!isset($this->persistent->acl)) {

        $acl = new AclList();

        ...

        //The acl is stored in session
        $this->persistent->acl = $acl;
    }

    return $this->persistent->acl;
}

By looking at your code, I am guessing you used the Phalcon INVO example for this SecurityPlugin? If so, refer to line 88. If not, this is a nice and easy example that can help you.

douluolan9101
douluolan9101 噢,伙计,谢谢你,我是如此盲目^^,对你的例子也是如此,我现在理解我的错误......
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问