How to use Expressions in Security, Routing, Services, and Validation
How to use Expressions in Security, Routing, Services, and Validation¶
New in version 2.4: The expression functionality was introduced in Symfony 2.4.
In Symfony 2.4, a powerful ExpressionLanguage component was added to Symfony. This allows us to add highly customized logic inside configuration.
The Symfony Framework leverages expressions out of the box in the following ways:
- Configuring services;
- Route matching conditions;
- Checking security (explained below) and access controls with allow_if;
- Validation.
For more information about how to create and work with expressions, see The Expression Syntax.
Security: Complex Access Controls with Expressions¶
New in version 2.4: The expression functionality was introduced in Symfony 2.4.
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()
{
if (!$this->get('security.context')->isGranted(new Expression(
'"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())'
))) {
throw $this->createAccessDeniedException();
}
// ...
}
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
. token
- The token object.
trust_resolver
- The
Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface
, object: you’ll probably use theis_*
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
- Equal to using
IS_AUTHENTICATED_ANONYMOUSLY
with theisGranted
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
.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.