WARNING: You are browsing the documentation for Symfony 2.7 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

Security: Complex Access Controls with Expressions

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:

use Symfony\Component\ExpressionLanguage\Expression;
// ...

public function indexAction()
    $this->denyAccessUnlessGranted(new Expression(
        '"ROLE_ADMIN" in roles or (user 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).
The array of roles the user has, including from the role hierarchy but not including the IS_AUTHENTICATED_* attributes (see the functions below).
The object (if any) that’s passed as the second argument to isGranted().
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”.
Equal to using IS_AUTHENTICATED_ANONYMOUSLY with the isGranted() function.
Similar, but not equal to IS_AUTHENTICATED_REMEMBERED, see below.
Similar, but not equal to IS_AUTHENTICATED_FULLY, see below.
Checks to see if the user has the given role - equivalent to an expression like 'ROLE_ADMIN' in roles.

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