Symfony voter: controlling access to an object
A Symfony voter decides on a permission that depends on the object targeted, this dish or this order, and on who asks: where a role is no longer enough.
final class PlatVoter extends Voter { protected function supports(string $attribute, mixed $subject): bool { return 'PLAT_MODIFIER' === $attribute && $subject instanceof Plat; } protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool { // The boss, or the dish's creator; otherwise, denied. } } // In the controller: #[IsGranted('PLAT_MODIFIER', 'plat')]
A role says what a user is, not whether they can edit a given resource. The voter answers two questions: supports(), do I handle this attribute and this subject; then voteOnAttribute(), is it allowed. Symfony asks every voter, and those that aren't concerned abstain. You call on it with #[IsGranted] and a subject, isGranted() in the controller or is_granted() in Twig. The trap: a supports() that never recognises its subject, for instance an instanceof on a wrongly imported class. The voter silently abstains, and access is denied to everyone.
The exercises have you write the voter that lets each of the tavern's cooks edit only their own dishes, the boss keeping all rights, then look, in a sabotaged security configuration, for the voter that no longer votes.
2 exercises work on this concept, by writing code in the browser.
In the tracks
- To each their own dishes Symfony for PHP developers · chapter 4: The keys to the tavern
- 🐉 Boss: the stolen keys Symfony for PHP developers · chapter 4: The keys to the tavern