New in Symfony 5.1: Simpler security attributes

Contributed by
Jules Pietri and Wouter De Jong
in #31189.

Checking the status of users in Symfony applications (anonymous, logged in, etc.) requires using security attributes such as IS_AUTHENTICATED_ANONYMOUSLY. These attributes are sometimes confusing because they don't define a state but a condition. For example, IS_AUTHENTICATED_REMEMBERED is true for "Remember Me" users but also for fully authenticated users.

That's why in Symfony 5.1 we've introduced new attributes that only check the user status. For example, to check inside a controller if the user is a "Remember Me" user:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// BEFORE
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')
    && !$this->isGranted('IS_AUTHENTICATED_FULLY')) {
    // ...
}

// AFTER
if ($this->isGranted('IS_REMEMBERED')) {
    // ...
}

Another example, which checks anonymous users inside Twig templates:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{# BEFORE #}
{% if is_granted('IS_AUTHENTICATED_ANONYMOUSLY')
    and not is_granted('IS_AUTHENTICATED_REMEMBERED')
    and not is_granted('IS_AUTHENTICATED_FULLY') %}
    {# ... #}
{% endif %}

{# AFTER #}
{% if is_granted('IS_ANONYMOUS') %}
    {# ... #}
{% endif %}

New Impersonation Attribute

Contributed by
Wouter De Jong
in #35858.

User impersonation allows you to browse the application logged in as another user. When impersonating other users, the currently logged in user gets a special security role called ROLE_PREVIOUS_ADMIN automatically. This is how you can detect if the current user is impersonating or not.

However, using security roles as attributes feels like a hack and moreover, the role name is not perfectly clear. That's why in Symfony 5.1 we've deprecated ROLE_PREVIOUS_ADMIN and introduced a new attribute called IS_IMPERSONATOR. Your code and templates will be much easier to understand now:

1
2
3
4
5
6
7
8
9
{# BEFORE #}
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
    <a href="...">Exit impersonation</a>
{% endif %}

{# AFTER #}
{% if is_granted('IS_IMPERSONATOR') %}
    <a href="...">Exit impersonation</a>
{% endif %}

Comments

Please note that the first section is not 100% correct:

The IS_AUTHENTICATED_* attributes define a minimal condition: IS_AUTHENTICATED_REMEMBERED is true when the user is authenticated using a remember cookie OR is fully authenticated.

The IS_* attributes define a specific state: IS_REMEMBERED is only true when the user is authenticated using a remember cookie.
@Wouter thanks for telling me about this error. You are completely right and I've updated the original content entirely. Thanks!
This is great! Code is now much clearer and easier to read.
Thanks you

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.