security.yml
security:
access_control:
- { path: ^/ }
RequestVoter.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Security;
class RequestVoter implements VoterInterface
{
/**
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @inheritDoc
*/
public function vote(TokenInterface $token, $subject, array $attributes)
{
if (!$subject instanceof Request) {
return self::ACCESS_ABSTAIN;
}
$route = $subject->attributes->get('_route');
$routeRole = $this->getRoleByRoute($route);
if ($this->security->isGranted($routeRole)) {
return self::ACCESS_GRANTED;
}
return self::ACCESS_DENIED;
}
protected function getRoleByRoute(string $route): string
{
// ...
}
}