Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 62 ยท Security

Authorization: Roles and Voters

Decide what a signed-in user may do in Symfony: roles, access_control, #[IsGranted], role hierarchy and custom voters, with runnable stand-ins for both.

Authentication answers "who are you?". Authorization answers the next question: "are you allowed to do this?". A signed-in customer should not open the admin area, and an author should be able to edit their own post but not somebody else's. Symfony gives you one question to ask everywhere, isGranted(attribute, subject), and a set of voters that answer it.

This lesson covers the simple tool (roles), the flexible tool (voters), the places where you ask the question (configuration, attributes, controllers and Twig), and it rebuilds the decision machinery in plain PHP so you can run it. It continues from users and firewalls and login forms and authenticators.

One question, many answers

Everything in Symfony's authorization layer goes through the access decision manager. You hand it two things:

  • an attribute: a string describing what you want to do, such as ROLE_ADMIN or POST_EDIT;
  • an optional subject: the thing you want to do it to, such as a Post object.

The manager asks every registered voter whether it can judge that pair. Each voter answers grant, deny or abstain (not my business). A strategy then turns the list of votes into one yes or no.

flowchart LR
    Q["isGranted('POST_EDIT', $post)"] --> M["Access decision manager"]
    M --> V1["RoleVoter<br/>(abstains: not a ROLE_)"]
    M --> V2["PostVoter<br/>(grants or denies)"]
    M --> V3["Other voters<br/>(abstain)"]
    V1 --> S["Strategy<br/>affirmative by default"]
    V2 --> S
    V3 --> S
    S --> R["true or false"]

The decision manager collects votes from every voter and applies a strategy to reach a single answer.

Roles: the simple tool

A role is a string that starts with ROLE_. Your user class returns them from getRoles(), and by convention every user also gets ROLE_USER automatically.

PHP
// src/Entity/User.php (real Symfony, read-only)
#[ORM\Column(type: 'json')]
private array $roles = [];

public function getRoles(): array
{
    $roles = $this->roles;
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

Roles work well for broad groups: ROLE_ADMIN, ROLE_EDITOR, ROLE_SUPPORT. They are a poor fit for rules such as "only the author", because a role does not know which post you are asking about. That is the job of voters.

Role hierarchy

An admin can usually do everything an editor can, and an editor everything a plain user can. Instead of giving admins three roles, declare the hierarchy once:

YAML
# config/packages/security.yaml (real Symfony, read-only)
security:
    role_hierarchy:
        ROLE_EDITOR: ROLE_USER
        ROLE_ADMIN: [ROLE_EDITOR, ROLE_SUPPORT]

A user with only ROLE_ADMIN now also passes checks for ROLE_EDITOR, ROLE_SUPPORT and ROLE_USER. Symfony follows the chain for you, so you can nest as deep as you like.

Running a role hierarchy

Symfony cannot run on this site, so here is a stand-in: a hierarchy that expands roles by walking the map, and path rules where the first match wins, the same way access_control behaves.

PHP Role hierarchy and access_control (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Alice (admin only) can reach every path because her single role expands to three. Bob only passes the rules that ask for ROLE_USER, and everybody can see /about because no rule matches it.

Where to ask the question

You can check access in four places. Use the outermost one that fits and fall through to the finer ones only when needed.

1. access_control in security.yaml. Path-based, checked by the firewall before any controller runs:

YAML
# config/packages/security.yaml (real Symfony, read-only)
security:
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/account, roles: ROLE_USER }

Rules are tried in order and the first match decides, so put specific paths before general ones.

2. #[IsGranted] on a controller or action. It sits right next to the code it protects:

PHP
// src/Controller/AdminController.php (real Symfony, read-only)
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_ADMIN')]
final class AdminController extends AbstractController
{
    #[Route('/admin/reports', name: 'admin_reports')]
    public function reports(): Response
    {
        // Only ROLE_ADMIN gets here.
    }

    #[Route('/admin/posts/{id}/edit', name: 'admin_post_edit')]
    #[IsGranted('POST_EDIT', subject: 'post')]
    public function edit(Post $post): Response
    {
        // Both checks passed: the class-level role AND the post voter.
    }
}

The subject: 'post' option names a controller argument (here filled by the Post entity from the route), and Symfony passes that object to the voters. You can also set statusCode to answer 404 instead of 403 when you prefer not to reveal that a page exists.

3. In code, when the answer decides what to do rather than whether to stop:

PHP
// real Symfony, read-only
$this->denyAccessUnlessGranted('POST_EDIT', $post);   // throws AccessDeniedException

if ($this->isGranted('ROLE_ADMIN')) {
    // show extra data
}

In a service, inject Symfony\Bundle\SecurityBundle\Security and call $security->isGranted(...) the same way.

4. In Twig, to hide buttons and links:

TWIG
{# real Symfony, read-only #}
{% if is_granted('POST_EDIT', post) %}
    <a href="{{ path('post_edit', {id: post.id}) }}">Edit</a>
{% endif %}

Hiding a link is cosmetic. Anyone can type the URL, so every action that changes data must be protected on the server with access_control, #[IsGranted] or a check in code. The Twig check only keeps the page tidy.

What a denial looks like

When a check fails, Symfony throws an AccessDeniedException. If the user is not logged in, the firewall's entry point sends them to your login page. If they are logged in but not allowed, they get a 403 page. You do not write that branching yourself.

Besides roles, three special attributes describe how the user signed in: IS_AUTHENTICATED_FULLY (logged in with credentials this session), IS_AUTHENTICATED_REMEMBERED (logged in, possibly via a remember-me cookie) and PUBLIC_ACCESS (everyone, including anonymous visitors, used to open a path inside a firewall).

Voters: rules that know the subject

A voter is a service with two jobs: say which attributes and subjects it understands, and decide. Extending the base Voter class makes both easy.

PHP
// src/Security/PostVoter.php (real Symfony, read-only)
namespace App\Security;

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

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

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

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        return match ($attribute) {
            self::VIEW => $subject->isPublished() || ($user instanceof User && $subject->getAuthor() === $user),
            self::EDIT => $user instanceof User && $subject->getAuthor() === $user,
            default => false,
        };
    }
}

Newer 7.x releases let voteOnAttribute() take an optional extra Vote argument for explaining a denial; the shape above works everywhere. With autoconfiguration (see services and the container) the class is tagged as a voter automatically as soon as it exists. There is nothing to register.

Notice that supports() returns false for attributes and subjects the voter does not own. The base class turns that into an abstain vote, so voters never interfere with one another. This is why PostVoter can ignore ROLE_ADMIN completely.

Strategies

If two voters disagree, the strategy decides. Symfony's default is affirmative: grant as soon as any voter grants. The others are consensus (the majority wins), unanimous (a single denial wins) and priority (the first voter that does not abstain wins). If every voter abstains, access is denied unless you set allow_if_all_abstain: true.

YAML
# config/packages/security.yaml (real Symfony, read-only)
security:
    access_decision_manager:
        strategy: unanimous
        allow_if_all_abstain: false

A voter stand-in you can run

This stand-in has a role voter, a post voter and a decision manager with two strategies. The classes are not Symfony's, but the grant, deny and abstain protocol is the same.

PHP Voters and strategies (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the grid row by row. Carol can see the published post but nothing about the draft; Bob can edit both of his posts but not delete them; Alice can do everything. The last lines show the abstain rule: when no voter understands ARCHIVE, the answer is false, which is the safe default.

Two stand-in simplifications to remember: real voters receive a token (not a user) and a call may carry several attributes at once, and real voters are usually tagged and collected by the container instead of being listed by hand.

Practical advice

  • Prefer attributes you invent over raw roles in controllers. POST_EDIT states intent and survives a change of policy; ROLE_ADMIN hard-codes who may do it.
  • Keep voters pure. They should read the user and subject and return a boolean. Avoid side effects, and load extra data only if you must.
  • Test voters directly. A voter is a small class with no framework dependencies in its logic, so it is easy to unit test with a few users and subjects.
  • Deny by default. End your access_control list with a catch-all for the protected area, and remember that no voter means no access.

Events are the next tool you will want when something should happen around a request, for example logging every denial, as you will see in the following lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a voter return when it does not recognise the attribute or subject?

    supports() returns false and the base Voter class converts that into an abstain vote, so unrelated voters never block each other.
  2. 2. Why is a role such as ROLE_ADMIN a poor fit for the rule 'only the author may edit this post'?

    Roles describe groups of users. Rules that depend on the object being accessed belong in a voter, which gets the subject.
  3. 3. With role_hierarchy ROLE_ADMIN: ROLE_EDITOR and ROLE_EDITOR: ROLE_USER, which checks pass for a user who only has ROLE_ADMIN?

    Symfony follows the hierarchy transitively, so the admin also holds the editor role and the user role.
  4. 4. You hide the Delete button in Twig with is_granted(). Is the delete action now protected?

    Twig checks only affect what is rendered. Protect the action itself with access_control, #[IsGranted] or a check in code.
  5. 5. If every voter abstains and allow_if_all_abstain is false, what is the result?

    Denying when nobody has an opinion is the safe default. Set allow_if_all_abstain to true only if you really want the opposite.

Summary

  • Authorization asks isGranted(attribute, subject); the access decision manager collects votes (grant, deny, abstain) from voters and applies a strategy (affirmative by default).
  • Roles start with ROLE_, suit broad groups, and can be nested with role_hierarchy.
  • Check access with access_control (paths), #[IsGranted] (controllers), denyAccessUnlessGranted() or the Security service (code) and is_granted() (Twig, cosmetic only).
  • Voters extend Voter, implement supports() and voteOnAttribute(), and handle rules that depend on the object, such as ownership.
  • If all voters abstain, access is denied unless allow_if_all_abstain is true.

Next up: Events and Listeners.