【问题标题】:Cakephp 3 and AuthenticationCakephp 3 和身份验证
【发布时间】:2016-08-24 07:53:47
【问题描述】:

有没有像 Cakephp 3 这样的简单方法来处理角色

APP控制器

public function isAuthorized($user)
{
    // Admin can access every action
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // Default deny
    return false;
}

POSTS 控制器

public function isAuthorized($user) {
    // All registered users can add posts
    if ($this->action === 'edit') {
        return true;
    }

    return parent::isAuthorized($user);
}

我从http://book.cakephp.org/3.0/en/controllers/components/authentication.html#testing-actions-protected-by-authcomponent 知道

$this->auth->deny('add');

正在做,但是如何添加用户/管理员?

【问题讨论】:

  • 你的问题不清楚。你想达到什么目标?也许管理员路由是你想要的book.cakephp.org/3.0/en/development/routing.html#Cake\Routing\Router::prefix
  • 我想限制具有作者角色的用户的访问权限。他们不应该删除帖子,也不应该查看/删除/添加用户。
  • 比你在 isAuthorized 方法中需要这样的东西if ($this->action == "add" && $user->role == "author") { return false; }

标签: authentication cakephp-3.0


【解决方案1】:

我通过 isAuthorised() 方法以非常简单的方式使用了 ACL 身份验证。希望对你有帮助。

AppController.php 你可以定义属性

/**
 * ACCESS CONTROL LIST BASED ON METHODS OF CLASS FOR USER ROLES
 */
var $accessControllList = array();

定义私有方法

private function _checkAccessControll() {
    if ($this->Auth->user('id')) {
        if (!isset($this->accessControllList) || empty($this->accessControllList)) {
            return true;
        }

        $action_name = $this->request->params['action'];
        $user_role = $this->Auth->user('role');
        if (isset($this->accessControllList['allowed']) && !empty($this->accessControllList['allowed']) && in_array($action_name, $this->accessControllList['allowed'])) {
            return true;
        } else if (isset($this->accessControllList['role_base'][$user_role]) && !empty($this->accessControllList['role_base'][$user_role]) && in_array($action_name, $this->accessControllList['role_base'][$user_role])) {
            return true;
        }

        throw new \Cake\Network\Exception\ForbiddenException(__('You not have access for this page'));
    }
    return true;
}

在 isAuthorized() 中添加以下行。

$this->_checkAccessControll();

在任何控制器中,您都需要将 ACL 与角色进行映射。给你 PostsController.php 文件如下

/**
 * List of all accessible Action from URL
* @var array
*/
var $accessControllList = array(
    'allowed' => array('view','index'), // allowed for any role.
    'role_base' => array(
        'administrator' => array('delete', 'approve'), //specially allowed for administrator only
        'publisher' => array('view','create','index','replyComment'), // specially allowed for publisher only
        'reader' => array('postComment','replyComment') // specially allowed for reader
    )
);

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多