Once a Symfony application grows past "admin can do everything, users can see their own data," if ($user->getId() === $post->getAuthorId()) checks start spreading into controllers, then into Twig templates, then into console commands. The day the rule changes (add a moderator role, only allow edits within 24 hours of publication), every one of those occurrences has to be found again, and one is always missed. Voters exist specifically to avoid this scenario.

The concrete problem

A multi-author blog with roles ROLE_USER, ROLE_EDITOR and ROLE_ADMIN. The business rule: an author can edit their own post as long as it is not published; an editor can edit any post, published or not; an admin can do everything, including delete. This rule has to apply identically in the controller (deny access to the edit route), in the template (hide the "Edit" button when the action would be denied), and potentially in an admin CLI command.

Why scattering authorization logic breaks in practice

The problem is not just aesthetic. An authorization rule duplicated across N places has N chances to silently drift apart:

  • The controller checks $user === $post->getAuthor(), but the template only checks is_granted('ROLE_EDITOR'), which visually shows a button the controller will later reject, or worse, the opposite: a button that works by accident because some secondary controller forgot the check entirely.
  • A new route (PDF export, post duplication) gets added without reusing the existing check, because the developer has no clear idea of where that check actually lives.
  • Unit tests for the business rule do not exist in isolation anywhere, since the rule is entangled with the controller's HTTP logic.

A Voter centralizes the decision "can this user perform this action on this subject" in a single place that can be tested independently of the HTTP framework.

Building the Voter

<?php
// src/Security/Voter/PostVoter.php
namespace App\Security\Voter;

use App\Entity\Post;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class PostVoter extends Voter
{
    public const EDIT = 'POST_EDIT';
    public const DELETE = 'POST_DELETE';
    public const VIEW = 'POST_VIEW';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, [self::EDIT, self::DELETE, self::VIEW], true)
            && $subject instanceof Post;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof User) {
            return false; // unauthenticated user: deny by default
        }

        /** @var Post $post */
        $post = $subject;

        return match ($attribute) {
            self::VIEW => $post->isPublished() || $this->isOwnerOrEditor($post, $user),
            self::EDIT => $this->canEdit($post, $user),
            self::DELETE => in_array('ROLE_ADMIN', $user->getRoles(), true),
            default => false,
        };
    }

    private function canEdit(Post $post, User $user): bool
    {
        if (in_array('ROLE_ADMIN', $user->getRoles(), true)
            || in_array('ROLE_EDITOR', $user->getRoles(), true)) {
            return true;
        }

        return $post->getAuthor() === $user && !$post->isPublished();
    }

    private function isOwnerOrEditor(Post $post, User $user): bool
    {
        return $post->getAuthor() === $user
            || in_array('ROLE_EDITOR', $user->getRoles(), true);
    }
}

The key detail in supports(): it only handles the attributes and subject type it actually knows about, returning false otherwise, so Symfony's AccessDecisionManager can query other Voters without conflict. voteOnAttribute() should never throw for an unhandled case: a match with an explicit default => false prevents a forgotten attribute from accidentally granting access.

Using the Voter in the controller

#[Route('/post/{id}/edit', name: 'post_edit')]
public function edit(Post $post, Request $request): Response
{
    $this->denyAccessUnlessGranted(PostVoter::EDIT, $post);

    // ... edit logic, reached only if access was granted
}

denyAccessUnlessGranted throws an AccessDeniedException (turned into a 403 by Symfony) when the Voter denies access, with no explicit condition needed in the controller itself. The business rule becomes a one-line call, identical across every route that needs it.

Using the Voter in Twig

{% if is_granted('POST_EDIT', post) %}
    <a href="{{ path('post_edit', {id: post.id}) }}">Edit</a>
{% endif %}
{% if is_granted('POST_DELETE', post) %}
    <a href="{{ path('post_delete', {id: post.id}) }}" class="text-danger">Delete</a>
{% endif %}

The Twig is_granted() function calls exactly the same Voter as the controller. This is what eliminates the drift between "what the button shows" and "what the controller actually allows": there is now a single source of truth for the rule.

Testing the Voter in isolation

// tests/Security/Voter/PostVoterTest.php
public function testAuthorCanEditUnpublishedPost(): void
{
    $author = new User();
    $post = (new Post())->setAuthor($author)->setPublished(false);

    $token = new UsernamePasswordToken($author, 'main', ['ROLE_USER']);
    $voter = new PostVoter();

    $this->assertSame(
        VoterInterface::ACCESS_GRANTED,
        $voter->vote($token, $post, [PostVoter::EDIT]),
    );
}

public function testAuthorCannotEditPublishedPost(): void
{
    $author = new User();
    $post = (new Post())->setAuthor($author)->setPublished(true);

    $token = new UsernamePasswordToken($author, 'main', ['ROLE_USER']);
    $voter = new PostVoter();

    $this->assertSame(
        VoterInterface::ACCESS_DENIED,
        $voter->vote($token, $post, [PostVoter::EDIT]),
    );
}

This is the benefit that justifies the detour: the authorization rule becomes testable in full isolation, with no HTTP kernel to boot, no database fixtures, just plain PHP objects and assertions.

The tradeoffs worth naming

  • One Voter vs multiple Voters per entity: a single Voter per entity type (as above) stays readable up to roughly ten attributes. Beyond that, or if role logic becomes cross-cutting across several entities (e.g. "a moderator can moderate everything"), it is better to extract that logic into a dedicated service injected into several Voters, rather than duplicating in_array('ROLE_ADMIN', ...) everywhere.
  • Business logic directly in voteOnAttribute vs delegating to the entity: putting $post->isPublished() in the Voter is fine for a simple visibility rule. If the rule gets more complex (a 24-hour window, a workflow state with several transitions), it is better to delegate to an entity method or a dedicated domain service, keeping the Voter a thin orchestration point rather than the holder of business rules untested anywhere else.
  • AccessDecisionManager strategy: Symfony defaults to affirmative (a single granting Voter is enough). If several Voters can apply to the same attribute with conflicting opinions, the unanimous strategy is safer for sensitive permissions, at the cost of a stricter configuration that needs revisiting whenever a new Voter is added.

When Voters are not enough

Voters cover entity-level or single-action authorization very well. For a permission system configurable by end users (fine-grained ACLs, resource sharing with custom per-team permissions, Google Drive style), the complexity goes beyond what hardcoded Voters can reasonably express: at that point a database-backed permission model with its own resolution engine is needed, with Voters reduced to querying that model instead of carrying the rule directly in PHP code.

Extracting a cross-cutting rule into a dedicated service

In a real project, several entities often share the same notion of "owner" or "privileged role." Duplicating in_array('ROLE_ADMIN', ...) across every Voter works at first, then becomes a source of drift the moment an intermediate role (ROLE_MODERATOR) needs to be added to some Voters and gets forgotten in others.

// src/Security/PermissionResolver.php
namespace App\Security;

use App\Entity\User;

class PermissionResolver
{
    public function hasElevatedAccess(User $user): bool
    {
        return array_intersect(['ROLE_ADMIN', 'ROLE_EDITOR'], $user->getRoles()) !== [];
    }

    public function isOwner(User $user, object $subject): bool
    {
        return method_exists($subject, 'getAuthor') && $subject->getAuthor() === $user;
    }
}
class PostVoter extends Voter
{
    public function __construct(private PermissionResolver $permissions) {}

    private function canEdit(Post $post, User $user): bool
    {
        if ($this->permissions->hasElevatedAccess($user)) {
            return true;
        }

        return $this->permissions->isOwner($user, $post) && !$post->isPublished();
    }
}

This decoupling has a useful side effect: PermissionResolver becomes injectable and testable independently of any single Voter, and a new Voter for a different entity (comments, attachments) can reuse the same elevated-role logic instead of copying it.

A common trap: checking authorization after the resource is already loaded

A recurring detail in code review: loading the resource before checking authorization exposes, even briefly, any business side effect tied to loading it (sending a notification email, incrementing a view counter) to a user who should never have had access to that resource in the first place.

#[Route('/post/{id}', name: 'post_show')]
public function show(Post $post): Response
{
    // Wrong order: a postLoad event subscriber may have already run
    $this->denyAccessUnlessGranted(PostVoter::VIEW, $post);

    return $this->render('post/show.html.twig', ['post' => $post]);
}

With Symfony's ParamConverter, the entity is hydrated before the method body even runs, so any Doctrine event tied to loading (postLoad) fires before the Voter check happens. If such an event carries a business side effect, either the authorization check needs to move earlier via #[IsGranted] on the route itself, or the loading side effects need to stay strictly neutral.

#[Route('/post/{id}', name: 'post_show')]
#[IsGranted(PostVoter::VIEW, subject: 'post')]
public function show(Post $post): Response
{
    return $this->render('post/show.html.twig', ['post' => $post]);
}

The #[IsGranted] attribute does not change the exact moment Doctrine hydration happens, but it makes the check visible right in the method signature, which is easier to audit in code review than a call buried inside the function body.

Takeaway

A Voter centralizes an authorization rule in one place, queried identically by the controller, Twig and console commands, which eliminates the silent drift between what the UI shows and what the backend actually allows. The real gain is not the Symfony syntax, it is making the business rule testable independently of the HTTP framework.