简体   繁体   中英

How to match url's against Symfony's security access control

Hi everyone im new to Symfony and have a simple problem.

In the security.yml file I've set some access controlled paths:

access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: .*settings, roles: ROLE_USER }
    - { path: ^/$, roles: ROLE_USER }
    - { path: ^/.*, roles: ROLE_ADMIN }

That so far works as i want to.

Now Im building a menu and want to hide show the navigation items based on its access, so how can i fetch this information?

There has to be some function like:

$securityContext->isUrlGranted( $this->generateUrl('homepage') );

Thanks for your help.

EDIT

Example:

// current user is ROLE_ADMIN:
$acl->isUrlGranted( 'foo/bar' ); // true
$acl->isUrlGranted( 'login' ); // true

// IS_AUTHENTICATED_ANONYMOUSLY
$acl->isUrlGranted( 'login' ); // true
$acl->isUrlGranted( 'something/else' ); // false

// ROLE_USER
$acl->isUrlGranted( 'settings/profile' ); // true
$acl->isUrlGranted( 'foo/bar' ); // false

etc..

Now there is no simple ways in Symfony get this information via one function.

To get it you can access security.access_control parameters in your application using security.access_map service.

But you can't request it from the container directly, because it's a private service, so have to inject it into another service.

And only then you will be able to write your own Twig extension with isUrlGranted() function.

PS: My answer is only a short summary of well written answer on the similar question.

if you are using twig in your view ( which should contain the menu ), you can test the user role with:

    {# my menu.twig.html #}

    {% if app.security.isGranted('ROLE_ADMIN', app.user) %}
        ....
    {% endif %}

You can do the same in your controller by the way, but i supposed that your layout contains the menu so i posted a twig answer. Tell me if it's relevant and helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM