Security: Complex Access Controls with Expressions

5.3 version
Symfony 5.3 is backed by JoliCode.

Security: Complex Access Controls with Expressions

See also

The best solution for handling complex authorization rules is to use the Voter System.

In addition to a role like ROLE_ADMIN, the isGranted() method also accepts an Symfony\Component\ExpressionLanguage\Expression object:

// src/Controller/MyController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Response;

class MyController extends AbstractController
    public function index(): Response
        $this->denyAccessUnlessGranted(new Expression(
            '"ROLE_ADMIN" in role_names or (not is_anonymous() and user.isSuperAdmin())'

        // ...

In this example, if the current user has ROLE_ADMIN or if the current user object’s isSuperAdmin() method returns true, then access will be granted (note: your User object may not have an isSuperAdmin() method, that method is invented for this example).

This uses an expression and you can learn more about the expression language syntax, see The Expression Syntax.

Inside the expression, you have access to a number of variables:

The user object (or the string anon if you’re not authenticated).
An array with the string representation of the roles the user has. This array includes any roles granted indirectly via the role hierarchy but it does not include the IS_AUTHENTICATED_* attributes (see the functions below).
The object (if any) that’s passed as the second argument to isGranted().
It stores the same value as object, so they are equivalent.
The token object.
The Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface, object: you’ll probably use the is_*() functions below instead.

Additionally, you have access to a number of functions inside the expression:

Returns true if the user is authenticated via “remember-me” or authenticated “fully” - i.e. returns true if the user is “logged in”.
Returns true if the user is anonymous. That is, the firewall confirms that it does not know this user’s identity. This is different from IS_AUTHENTICATED_ANONYMOUSLY, which is granted to all users, including authenticated ones.
Similar, but not equal to IS_AUTHENTICATED_REMEMBERED, see below.
Equal to checking if the user has the IS_AUTHENTICATED_FULLY role.
Checks if the user has the given permission. Optionally accepts a second argument with the object where permission is checked on. It’s equivalent to using the isGranted() method from the security service.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.