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

useSymfony\Component\ExpressionLanguage\Expression;// ...publicfunctionindexAction(){$this->denyAccessUnlessGranted(newExpression('"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:

user

The user object (or the string anon if you're not authenticated).

roles

The array of roles the user has, including from the
role hierarchy but not including the
IS_AUTHENTICATED_* attributes (see the functions below).

object

The object (if any) that's passed as the second argument to isGranted().

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

Equal to using IS_AUTHENTICATED_ANONYMOUSLY with the isGranted() function.

is_remember_me

Similar, but not equal to IS_AUTHENTICATED_REMEMBERED, see below.

is_fully_authenticated

Similar, but not equal to IS_AUTHENTICATED_FULLY, see below.

has_role

Checks to see if the user has the given role - equivalent to an expression like
'ROLE_ADMIN' in roles.

is_remember_me is different than checking IS_AUTHENTICATED_REMEMBERED

The is_remember_me() and is_authenticated_fully() functions are similar
to using IS_AUTHENTICATED_REMEMBERED and IS_AUTHENTICATED_FULLY
with the isGranted() function - but they are not the same. The
following shows the difference:

Here, $access1 and $access2 will be the same value. Unlike the
behavior of IS_AUTHENTICATED_REMEMBERED and IS_AUTHENTICATED_FULLY,
the is_remember_me() function only returns true if the user is authenticated
via a remember-me cookie and is_fully_authenticatedonly returns
true if the user has actually logged in during this session (i.e. is
full-fledged).