【发布时间】:2016-07-28 08:05:11
【问题描述】:
我对 Symfony 还是很陌生。我正在尝试在管理区域使用选民。
我希望管理员 (ROLE_ADMIN) 只有在他是超级管理员 (ROLE_SUPER_ADMIN) 时才能删除(移除)用户。
我的防火墙似乎工作正常,因为我可以登录管理区域并做我想做的事,直到我不使用投票者。这是我当前用户对象的转储:
User {#300 ▼
-id: 1
-password: "$2y$13$e3LL2N/pYGrGn.7EFikqSuAMSkLolcnggtf1HsBgNMzdXnal1AIua"
-username: "JustMe"
-email: "me@me.fr"
-isActive: true
-roles: array:1 [▼
0 => "ROLE_ADMIN"
]
}
一旦我在控制器中使用了denyUnlessGranted(),我就会得到这个异常:
DEBUG - Access denied, the user is neither anonymous, nor remember-me.
ERROR - Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: "Access Denied." at /Volumes/Work/MAMP htdocs/a-symfony-re/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php line 119
这是我的安全配置:
role_hierarchy:
ROLE_AUTHOR: ROLE_USER
ROLE_EDITOR: ROLE_AUTHOR
ROLE_ADMIN : [ROLE_USER, ROLE_ALLOWED_TO_SWITCH]
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
pattern: ^/
provider: app_users_provider
form_login:
login_path: jst_login
check_path: jst_login_check
logout:
path: jst_logout
target: /
access_decision_manager:
strategy: unanimous
这是我的控制器中的一个基本操作,在不使用投票器之前可以正常工作:
public function deleteUserAction(User $user)
{
$this->denyAccessUnlessGranted('delete', $user);
$currentUser = $this->getUser();
$role = $currentUser->getRoles[0];
return new Response('Delete User AppBundle:AdminController:deleteUser : '.$role);
}
这是非常简单的选民:
namespace AppBundle\Security;
use AppBundle\Entity\User;
use AppBundle\Entity\Role;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class UserVoter extends Voter
{
const EDIT = 'edit';
const DELETE = 'delete';
const CREATE = 'create';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface, $decisionManager)
{
$this->decisionManager = $decisionManager;
}
public function support($attribute, $subject)
{
if (!in_array($attribute, array(selt::DELETE))) {
return false;
}
if (!$subject instanceOf USER) {
return false;
}
return true;
}
public function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$currentUser = $token->getUser();
$user = $subject;
if (!$currentUser instanceOf User) {
return false;
}
switch ($attribute) {
case self::DELETE :
//return $this->canDelete( $token );
return $this->canDelete($user, $currentUser);
break;
default:
throw new \LogicException('this code shoudn\'t be executed');
}
}
private function canDelete($user, $currentUser)
{
//return $this->decisionManager->decide( $token, array( 'ROLE_ADMIN' ) );
return $currentUser->getRoles()[0] == 'SUPER_ADMIN';
}
}
如您所见,我已经尝试使用 AccessDecisionManagerInterface 没有结果..
Et bien heuuu .. 有什么帮助吗? ;-)
谢谢!
【问题讨论】:
-
你的
support函数中有错字:selt::DELETE应该是self::DELETE? -
你说得对!但仍然有这个异常..