2013-08-19 1 views
1

Вот мое bjyauthorize.global.php содержанияконфигурация в маршрутизации на основе ролей с помощью BjyAuthorize не работает

<?php 

return array(
'bjyauthorize' => array(

    // set the 'guest' role as default (must be defined in a role provider) 
    // 'default_role' => 'guest', 

    /* this module uses a meta-role that inherits from any roles that should 
    * be applied to the active user. the identity provider tells us which 
    * roles the "identity role" should inherit from. 
    * 
    * for ZfcUser, this will be your default identity provider 
    */ 
    'identity_provider' => 'BjyAuthorize\Provider\Identity\ZfcUserZendDb', 

    /* If you only have a default role and an authenticated role, you can 
    * use the 'AuthenticationIdentityProvider' to allow/restrict access 
    * with the guards based on the state 'logged in' and 'not logged in'. 
    */ 
     // 'default_role'  => 'guest',   // not authenticated 
     // 'authenticated_role' => 'user',   // authenticated 
     // 'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider', 


    /* role providers simply provide a list of roles that should be inserted 
    * into the Zend\Acl instance. the module comes with two providers, one 
    * to specify roles in a config file and one to load roles using a 
    * Zend\Db adapter. 
    */ 
    'role_providers' => array(

     /* here, 'guest' and 'user are defined as top-level roles, with 
     * 'admin' inheriting from user 
     */ 
     'BjyAuthorize\Provider\Role\Config' => array(
      'admin' => array(), 
      'guest' => array() 
     ), 

     // this will load roles from the user_role table in a database 
     // format: user_role(role_id(varchar), parent(varchar)) 
     'BjyAuthorize\Provider\Role\ZendDb' => array(
      'table'    => 'user_role', 
      'role_id_field'  => 'roleId', 
      'parent_role_field' => 'parent_id', 
     ), 

     // this will load roles from the 'BjyAuthorize\Provider\Role\Doctrine' 
     // service 
     // 'BjyAuthorize\Provider\Role\Doctrine' => array(), 
    ), 

    // resource providers provide a list of resources that will be tracked 
    // in the ACL. like roles, they can be hierarchical 
    'resource_providers' => array(
     // 'BjyAuthorize\Provider\Resource\Config' => array(
     //  'pants' => array(), 
     //), 

     'BjyAuthorize\Provider\Resource\Config' => array(
      'Collections\Controller\CollectionsController' => array('admin'), 
     ), 
    ), 

    /* rules can be specified here with the format: 
    * array(roles (array), resource, [privilege (array|string), assertion]) 
    * assertions will be loaded using the service manager and must implement 
    * Zend\Acl\Assertion\AssertionInterface. 
    * *if you use assertions, define them using the service manager!* 
    */ 
    'rule_providers' => array(
     'BjyAuthorize\Provider\Rule\Config' => array(
      'allow' => array(
       // allow guests and users (and admins, through inheritance) 
       // the "wear" privilege on the resource "pants" 
       // array(array('guest', 'user'), 'pants', 'wear') 
       array(array('admin'), 'Collections\Controller\CollectionsController', 'index') 
      ), 

      // Don't mix allow/deny rules if you are using role inheritance. 
      // There are some weird bugs. 
      'deny' => array(
       // ... 
       // array(array('admin', 'guest'), 'collections', 'add') 
      ), 
     ), 
    ), 

    /* Currently, only controller and route guards exist 
    * 
    * Consider enabling either the controller or the route guard depending on your needs. 
    */ 
    'guards' => array(
     /* If this guard is specified here (i.e. it is enabled), it will block 
     * access to all controllers and actions unless they are specified here. 
     * You may omit the 'action' index to allow access to the entire controller 
     */ 
     'BjyAuthorize\Guard\Controller' => array(
      array('controller' => 'index', 'action' => 'index', 'roles' => array('admin','guest')), 
      array('controller' => 'index', 'action' => 'stuff', 'roles' => array('admin')), 
      array('controller' => 'Collections\Controller\CollectionsController', 'roles' => array('admin', 'guest')), 

      // You can also specify an array of actions or an array of controllers (or both) 
      // allow "guest" and "admin" to access actions "list" and "manage" on these "index", 
      // "static" and "console" controllers 
      // array(
      //  'controller' => array('index', 'static', 'console'), 
      //  'action' => array('list', 'manage'), 
      //  'roles' => array('guest', 'admin') 
      //), 
      array('controller' => 'zfcuser', 'roles' => array('admin', 'guest')), 
      // Below is the default index action used by the ZendSkeletonApplication 
      array('controller' => 'Application\Controller\Index', 'roles' => array('guest', 'admin')), 
     ), 

     /* If this guard is specified here (i.e. it is enabled), it will block 
     * access to all routes unless they are specified here. 
     */ 
     'BjyAuthorize\Guard\Route' => array(
      array('route' => 'zfcuser', 'roles' => array('admin', 'guest')), 
      array('route' => 'zfcuser/logout', 'roles' => array('admin', 'guest')), 
      array('route' => 'zfcuser/login', 'roles' => array('admin', 'guest')), 
      array('route' => 'zfcuser/register', 'roles' => array('guest', 'admin')), 
      // Below is the default index action used by the ZendSkeletonApplicationarray('route' => 'zfcuser/register', 'roles' => array('guest', 'admin')), 
      array('route' => 'collections/index', 'roles' => array('guest', 'admin')), 
      array('route' => 'home', 'roles' => array('guest', 'admin')), 
     ), 
    ), 
), 
); 

У меня есть базы данных структуры, как это:

-- 
-- Table structure for table `user` 
-- 

CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
`username` varchar(255) DEFAULT NULL, 
`email` varchar(255) DEFAULT NULL, 
`display_name` varchar(50) DEFAULT NULL, 
`password` varchar(128) NOT NULL, 
`state` smallint(5) unsigned DEFAULT NULL, 
PRIMARY KEY (`id`), 
UNIQUE KEY `username` (`username`), 
UNIQUE KEY `email` (`email`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; 

-- 
-- Dumping data for table `user` 
-- 

INSERT INTO `user` (`id`, `username`, `email`, `display_name`, `password`, `state`) VALUES 
(1, NULL, '[email protected]', NULL, '$2y$14$fL.K0rieXO.kHsHfOogH8Oaf..C.1GsYqEB49A3Dmxy9ZiMhWHx7.', NULL); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `user_role` 
-- 

CREATE TABLE IF NOT EXISTS `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`roleId` varchar(255) NOT NULL, 
`is_default` tinyint(1) NOT NULL, 
`parent_id` varchar(255) DEFAULT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; 

-- 
-- Dumping data for table `user_role` 
-- 

INSERT INTO `user_role` (`id`, `roleId`, `is_default`, `parent_id`) VALUES 
(1, 'admin', 1, 'admin'), 
(2, 'guest', 1, 'admin'); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `user_role_linker` 
-- 

CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` int(11) unsigned NOT NULL, 
`role_id` int(11) NOT NULL, 
PRIMARY KEY (`user_id`,`role_id`), 
KEY `role_id` (`role_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

-- 
-- Dumping data for table `user_role_linker` 
-- 

INSERT INTO `user_role_linker` (`user_id`, `role_id`) VALUES 
(1, 1); 

Я измененный столбец пользователя таблица в зависимости от этого issue. И я изменил Mapper из ZfcUser для user_id в id. Он работает правильно, потому что он не показывает никаких ошибок.

Несмотря на отсутствие каких-либо ошибок, я всегда получаю «403 Forbidden» для любого модуля, который я посещаю (/ user и/collections), за исключением страницы входа (zfcuser/login) перед входом в систему.

У меня есть сомнение в базе данных для данных таблицы user_role_linker. Я не нашел надлежащей документации для ввода данных ролей для таблицы user_role в BjyAuth library. Предложите мне, есть ли какая-либо неверная конфигурация в файле конфигурации или в таблицах базы данных или что-то еще, о чем здесь не упоминается.

ответ

0

Возможно, вы пытаетесь сделать слишком много, не зная, правильно ли установлены основы. Не полный ответ, но я бы предложил следующее:

  • Установка Zend Framework Developer Tools ( https://github.com/zendframework/ZendDeveloperTools) раз запускался он имеет панель инструментов в нижней части страницы, которая расскажет вам, какую роль вы в настоящее время. Это также полезно для множества других вещей. Предполагая, что у вас есть соответствующая роль, когда вы вошли в систему, только настройте одного охранника за раз. то есть. Вы в настоящее время есть и «BjyAuthorize \ Guard \ Controller» и «BjyAuthorize \ Guard \ Route» Установка

  • Вы можете работать только с одной или другой из них, чтобы начать, и когда у вас есть один работает, то вы можете протестировать Другие. Просто удалите или закомментируйте нужный раздел в bjyauthorize.global.php.

Обратите внимание, что поведение заключается в том, что если вы включите охранники, все, что не указано, заблокировано.

Не видя своих контроллеров и маршрутов, я не знаю, правильна ли какая-либо конфигурация выше, но, возможно, было бы безопаснее дважды проверять имена маршрутов и использовать полные имена контроллеров, например. вместо

array('controller' => 'index', 

попробовать

array('controller' => 'YourModuleName\Controller\IndexController', 

Я надеюсь, что это какая-то помощь.

Кроме того, если вы в конечном итоге используете Doctrine ORM https://github.com/manuakasam/SamUser - это отличный модуль, который легко объединяет BjyAuthorize, ZFcuser и Doctrine.

Fin

+0

У меня есть настройка конфигурации ролей и маршруты по вашему предложению, но вывод по-прежнему остается таким же. У меня есть эта ошибка при просмотре панели инструментов разработчика Zend Framework: Ошибка. Для использования этой функции вам необходимо установить или включить профили Zend \ Db Profiler @ bjyoungblood. Есть идеи об этом? – regeint

+0

Эта ошибка относится только к Profiler Profiler, что не важно для текущей проблемы. Вы видите справа от нее значок, указывающий, какую роль пользователя вы сейчас используете? Если ваши настройки могут быть неправильными. – Finbarr

+0

Да, есть значок с меткой «Гость». Когда я курю значок, он показывает: ByjAuthorize Роли идентичности -1 Роль: гость Бу роль текущего зарегистрированного пользователя не гость, его администратор. роль гостя всегда видна, даже если пользователь не вошел (на странице входа). – regeint

1

Проблема с user_role_linker таблицы, feilds role_id должен быть varchar, а затем int. Я была такая же проблема. Проверьте следующий дамп для данных образца.

CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` int(11) unsigned NOT NULL, 
`role_id` varchar(128) NOT NULL, 
PRIMARY KEY (`user_id`,`role_id`), 
KEY `role_id` (`role_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

-- 
-- Dumping data for table `user_role_linker` 
-- 

INSERT INTO `user_role_linker` (`user_id`, `role_id`) VALUES(1, 'admin');