Symfony Security Authorization

There are several way to make authorization on your site with Symfony.
First is in your security.yml on the same level as firewalls tag:

        - { path: ^/admin, roles: ROLE_USER }

This will block all users that don’t have ‘ROLE_USER’ to admin page.

Second option is to use Controller. Inside Method insert:

            throw $this->createAccessDeniedException('GET OUT!');

Or like this:


This will deny access to all users that don’t have ‘ROLE_ADMIN’ to this method.

You can also use annotations:

* @Security("is_granted('ROLE_ADMIN')")

Annotations also work if you add them to the Class. So they will block all users that don’t have ‘ROLE_ADMIN’ to this class.

Dynamic Roles

If you need ability to assign different permissions to different users you need to go little further. In User Entity add:

     * @ORM\Column(type="json_array")
    private $roles = [];

     * @return array
    public function getRoles()
        $roles = $this->roles;
        if (!in_array('ROLE_USER', $roles)) {
           $roles[] = 'ROLE_USER';

        return $roles;

     * @param mixed $roles
    public function setRoles($roles)
        $this->roles = $roles;

Generate the migration for new field.

# php bin/console doctrine:migrations:diff
# php bin/console doctrine:migrations:migrate

Security check in Twig


<h1>Welcome {{ app.user ? : 'Bro'}}!</h1>

                {% if is_granted('ROLE_USER') %}
                    <li><a href="{{ path('security_logout') }}">Logout</a></li>
                {% else %}
                    <li><a href="{{ path('security_login') }}">Login</a></li>
                {% endif %}.

Role Hierarchy

If you have many different sections that have to be accessed by many different types of users.

In security.yml on the same level as firewalls tag:


To Controller class add annotation:

 * @Security("is_granted('ROLE_MANAGE_GENUS')")

That is how you can give different permissions to a specific role.


Switching user is really simple Symfony. In security.yml on the same level as anonymous tag in main section, add switch_user:

            anonymous: ~

                path: /logout

            switch_user: ~

Also you need to give permission to switch users by adding ROLE_ALLOWED_TO_SWITCH:


Make sure that you have configured the Entity user provider section:

            entity: { class: AppBundle\Entity\User, property: email }

The property sets the field by what we want to be impersonated.

To switch user add to URL ?_switch_user= and the email of the user you want to impersonate.


To stop impersonation add to any URL:


Leave a Reply

Your email address will not be published. Required fields are marked *