Security: Complex Access Controls with Expressions
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
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 Expression object:
1 2 3 4 5 6 7 8 9 10 11
use Symfony\Component\ExpressionLanguage\Expression;
// ...
public function indexAction()
{
$this->denyAccessUnlessGranted(new Expression(
'"ROLE_ADMIN" in roles 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:
user
-
The user object (or the string
anon
if you're not authenticated). roles
-
The array of 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). object
-
The object (if any) that's passed as the second argument to
isGranted()
. token
- The token object.
trust_resolver
-
The AuthenticationTrustResolverInterface,
object: you'll probably use the
is_*()
functions below instead.
Additionally, you have access to a number of functions inside the expression:
is_authenticated()
-
Returns
true
if the user is authenticated via "remember-me" or authenticated "fully" - i.e. returns true if the user is "logged in". is_anonymous()
-
Returns
true
if the user is anonymous. That is, the firewall confirms that it does not know this user's identity. This is different fromIS_AUTHENTICATED_ANONYMOUSLY
, which is granted to all users, including authenticated ones. is_remember_me()
-
Similar, but not equal to
IS_AUTHENTICATED_REMEMBERED
, see below. is_fully_authenticated()
-
Equal to checking if the user has the
IS_AUTHENTICATED_FULLY
role. has_role()
-
Checks to see if the user has the given role - equivalent to an expression like
'ROLE_ADMIN' in roles
.