Symfony2 - set security access_control to allow on

2019-04-29 11:43发布

问题:

Let's say I have my access_control block under the security.yml:

access_control:
    - { path: ^/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/reset-password, roles: IS_AUTHENTICATED_ANONYMOUSLY }

In this case everyone is alowed to enter homepage and reset-password pages. But I would like to allow these pages only for users authenticated anonymously. Fully authenticated users should get an 403 access denied error or 404 page not found.

According documentation with allow_if I should be ablo to create role expressions to define access. But if I do it like this:

access_control:
    - { path: ^/reset-password, allow_if: "has_role('IS_AUTHENTICATED_ANONYMOUSLY') and not has_role('IS_AUTHENTICATED_FULLY')" }

Now following the idea fully authenticated users (logged in) shouldn't be allowed to access the page and anonymously authenticated should be able to access, but, unfortunatelly, none of users are able to access it...

Any ideas what I am missing?

UPDATE

This got it working as suggested bellow by correct answer:

- { path: ^/reset-password, allow_if: "is_anonymous() and !is_authenticated()" }

回答1:

Are you sure you can test IS_* using has_role()? These act like roles but they're not roles. Maybe that's why it always returns false:

  • http://symfony.com/doc/current/security.html#checking-to-see-if-a-user-is-logged-in-is-authenticated-fully

It seems like you should better use is_anonymous() and is_authenticated() custom functions in the allow_if expression.

  • http://symfony.com/doc/current/expressions.html#security-expression-variables