发布于 2015-08-27 16:43:24 | 148 次阅读 | 评论: 0 | 来源: 网络整理
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:
For more information about how to create and work with expressions, see The Expression Syntax.
In addition to a role like ROLE_ADMIN
, the isGranted
method also
accepts an Expression
object:
use SymfonyComponentExpressionLanguageExpression;
// ...
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:
user
anon
if you’re not authenticated).roles
IS_AUTHENTICATED_*
attributes (see the functions below).object
isGranted
.token
trust_resolver
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
true
if the user is authenticated via “remember-me” or authenticated
“fully” - i.e. returns true if the user is “logged in”.is_anonymous
IS_AUTHENTICATED_ANONYMOUSLY
with the isGranted
function.is_remember_me
IS_AUTHENTICATED_REMEMBERED
, see below.is_fully_authenticated
IS_AUTHENTICATED_FULLY
, see below.has_role
'ROLE_ADMIN' in roles
.