Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Components
  4. Security
  5. Authorization
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Access Decision Manager
  • Voters
    • AuthenticatedVoter
    • RoleVoter
    • RoleHierarchyVoter
  • Roles
  • Using the decision manager
    • The Access Listener
    • Security context

Authorization

Edit this page

Warning: You are browsing the documentation for Symfony 2.0, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

Authorization

When any of the authentication providers (see Authentication) has verified the still-unauthenticated token, an authenticated token will be returned. The authentication listener should set this token directly in the SecurityContextInterface using its setToken() method.

From then on, the user is authenticated, i.e. identified. Now, other parts of the application can use the token to decide whether or not the user may request a certain URI, or modify a certain object. This decision will be made by an instance of AccessDecisionManagerInterface.

An authorization decision will always be based on a few things:

  • The current token
    For instance, the token's getRoles() method may be used to retrieve the roles of the current user (e.g. ROLE_SUPER_ADMIN), or a decision may be based on the class of the token.
  • A set of attributes
    Each attribute stands for a certain right the user should have, e.g. ROLE_ADMIN to make sure the user is an administrator.
  • An object (optional)
    Any object on which for which access control needs to be checked, like an article or a comment object.

Access Decision Manager

Since deciding whether or not a user is authorized to perform a certain action can be a complicated process, the standard AccessDecisionManager itself depends on multiple voters, and makes a final verdict based on all the votes (either positive, negative or neutral) it has received. It recognizes several strategies:

  • affirmative (default)
    grant access as soon as any voter returns an affirmative response;
  • consensus
    grant access if there are more voters granting access than there are denying;
  • unanimous
    only grant access if none of the voters has denied access;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;

// instances of Symfony\Component\Security\Core\Authorization\Voter\VoterInterface
$voters = array(...);

// one of "affirmative", "consensus", "unanimous"
$strategy = ...;

// whether or not to grant access when all voters abstain
$allowIfAllAbstainDecisions = ...;

// whether or not to grant access when there is no majority (applies only to the "consensus" strategy)
$allowIfEqualGrantedDeniedDecisions = ...;

$accessDecisionManager = new AccessDecisionManager(
    $voters,
    $strategy,
    $allowIfAllAbstainDecisions,
    $allowIfEqualGrantedDeniedDecisions
);

Voters

Voters are instances of VoterInterface, which means they have to implement a few methods which allows the decision manager to use them:

  • supportsAttribute($attribute)
    will be used to check if the voter knows how to handle the given attribute;
  • supportsClass($class)
    will be used to check if the voter is able to grant or deny access for an object of the given class;
  • vote(TokenInterface $token, $object, array $attributes)
    this method will do the actual voting and return a value equal to one of the class constants of VoterInterface, i.e. VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED or VoterInterface::ACCESS_ABSTAIN;

The security component contains some standard voters which cover many use cases:

AuthenticatedVoter

The AuthenticatedVoter voter supports the attributes IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED, and IS_AUTHENTICATED_ANONYMOUSLY and grants access based on the current level of authentication, i.e. is the user fully authenticated, or only based on a "remember-me" cookie, or even authenticated anonymously?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;

$anonymousClass = 'Symfony\Component\Security\Core\Authentication\Token\AnonymousToken';
$rememberMeClass = 'Symfony\Component\Security\Core\Authentication\Token\RememberMeToken';

$trustResolver = new AuthenticationTrustResolver($anonymousClass, $rememberMeClass);

$authenticatedVoter = new AuthenticatedVoter($trustResolver);

// instance of Symfony\Component\Security\Core\Authentication\Token\TokenInterface
$token = ...;

// any object
$object = ...;

$vote = $authenticatedVoter->vote($token, $object, array('IS_AUTHENTICATED_FULLY');

RoleVoter

The RoleVoter supports attributes starting with ROLE_ and grants access to the user when the required ROLE_* attributes can all be found in the array of roles returned by the token's getRoles() method:

1
2
3
4
5
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;

$roleVoter = new RoleVoter('ROLE_');

$roleVoter->vote($token, $object, 'ROLE_ADMIN');

RoleHierarchyVoter

The RoleHierarchyVoter extends RoleVoter and provides some additional functionality: it knows how to handle a hierarchy of roles. For instance, a ROLE_SUPER_ADMIN role may have subroles ROLE_ADMIN and ROLE_USER, so that when a certain object requires the user to have the ROLE_ADMIN role, it grants access to users who in fact have the ROLE_ADMIN role, but also to users having the ROLE_SUPER_ADMIN role:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

$hierarchy = array(
    'ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_USER'),
);

$roleHierarchy = new RoleHierarchy($hierarchy);

$roleHierarchyVoter = new RoleHierarchyVoter($roleHierarchy);

Note

When you make your own voter, you may of course use its constructor to inject any dependencies it needs to come to a decision.

Roles

Roles are objects that give expression to a certain right the user has. The only requirement is that they implement RoleInterface, which means they should also have a getRole() method that returns a string representation of the role itself. The default Role simply returns its first constructor argument:

1
2
3
4
5
6
use Symfony\Component\Security\Core\Role\Role;

$role = new Role('ROLE_ADMIN');

// will echo 'ROLE_ADMIN'
echo $role->getRole();

Note

Most authentication tokens extend from AbstractToken, which means that the roles given to its constructor will be automatically converted from strings to these simple Role objects.

Using the decision manager

The Access Listener

The access decision manager can be used at any point in a request to decide whether or not the current user is entitled to access a given resource. One optional, but useful, method for restricting access based on a URL pattern is the AccessListener, which is one of the firewall listeners (see The Firewall and Security Context) that is triggered for each request matching the firewall map (see The Firewall and Security Context).

It uses an access map (which should be an instance of AccessMapInterface) which contains request matchers and a corresponding set of attributes that are required for the current user to get access to the application:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use Symfony\Component\Security\Http\AccessMap;
use Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\Security\Http\Firewall\AccessListener;

$accessMap = new AccessMap();
$requestMatcher = new RequestMatcher('^/admin');
$accessMap->add($requestMatcher, array('ROLE_ADMIN'));

$accessListener = new AccessListener(
    $securityContext,
    $accessDecisionManager,
    $accessMap,
    $authenticationManager
);

Security context

The access decision manager is also available to other parts of the application via the isGranted() method of the SecurityContext. A call to this method will directly delegate the question to the access decision manager:

1
2
3
4
5
6
7
8
9
10
11
use Symfony\Component\Security\SecurityContext;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

$securityContext = new SecurityContext(
    $authenticationManager,
    $accessDecisionManager
);

if (!$securityContext->isGranted('ROLE_ADMIN')) {
    throw new AccessDeniedException();
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Take the exam at home

    Take the exam at home

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Nebojša Kamber, a Symfony contributor

    Thanks Nebojša Kamber for being a Symfony contributor

    2 commits • 4 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia