Domanda

I'm looking for a working solution, to hide pages from authenticated users in symfony. Unfortunately, the default user roles are staggered. The following configuration does not work:

# app/config/security.yml
access_control:

    # This rules works not:
    - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }

    # This rule works:
    - { path: ^/logout$, role: roles: [ROLE_USER] } 

For my opinion, this ruleset should end up in a HTTP 404 Unauthorized after visiting /login or /register as a authenticated user (UsernamePasswordToken) - but it does not!

After some reasearch, I found more information. According to Symfony 2 documentation, users are automatically given one of the following roles depending on how they are authenticated:

  1. IS_AUTHENTICATED_REMEMBERED
  2. IS_AUTHENTICATED_ANONYMOUSLY
  3. IS_AUTHENTICATED_FULLY

If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.

enter image description here

In other words: There seems to be no possible way, to hide pages from a authenticated user...


1. Possible solution - Use a static role (does not work...)

Using the access control role IS_ANONYMOUS could be great option, but it does not work for paths behind a Firewall: Symfony will append a AnonymousToken to your session each time you visit any page behind ^/:

# app/config/security.yml
security:
    firewalls:
        main:
            pattern: ^/
...

2. Possible solution - Edit all controllers (takes way too long...)

I ended up rewriting all controllers (.....) and implemented custom, hard-coded access rules into the controllers.


I hope, somebody has a smiliar problem and a simple stupid solution.

È stato utile?

Soluzione

You can easily solve this with the use of the expression-language component ( symfony ~2.4):

access_control:
    - { path: ^/whatever, allow_if: "!is_fully_authenticated()" }

For symfony <2.4 you can use JMSSecurityExtraBundle which provides expression-based security rules aswell.

request, token and user are the variables you have access to and is_anonymous(), is_authenticated(), is_fully_authenticated(), is_rememberme(), and has_role() are the functions defined in this context.

Read more about the expression-language:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top