-->

Multiple roles required for same url in symfony 2

2019-04-10 04:25发布

问题:

This is how my security.yml looks like for access control list:

access_control:
    - { path: ^/admin, roles: IS_AUTHENTICATED_FULLY }
    - { path: ^/admin, roles: ROLE_ADMIN }

What I want to do is that user must have both roles (ROLE_ADMIN and IS_AUTHENTICATED_FULLY) in order to access the path as defined. But with above rules, if the user has any one of the role, the user can access the path as defined which i dont want. I also tried giving rule as follow with no success:

 - { path: ^/admin, roles:[ROLE_ADMIN,IS_AUTHENTICATED_FULLY] }

How can I add rule that requires user to have both roles in order to access the path defined ?

回答1:

IS_AUTHENTICATED_FULLY

returns true when ever a user is actually authenticated.

Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role.

So if a user has a role ROLE_ADMIN and is logged in, he is fully authenticated. As a result there is no need to set this requirement:

- { path: ^/admin, roles: IS_AUTHENTICATED_FULLY }

because you have (see below) which includes beeing fully authenticated

- { path: ^/admin, roles: ROLE_ADMIN }

And

- { path: ^/admin, roles: IS_AUTHENTICATED_FULLY }

will allow any user to see the admin section.

Read: http://symfony.com/doc/current/book/security.html



回答2:

Looking at the problem itself, not at your specific situation.

If you need user to have all specified roles to access some path, this needs more configuration, as default RoleVoter grants access if current security token has at least one of specified roles.

RoleVoter grants access if token has at least one of passed roles, but Security component passes each of specified roles individually to each of the voters. So to change OR behaviour to AND behaviour all you need to do is to change decition manager strategy:

# app/config/security.yml
security:
    access_decision_manager:
        # strategy can be: affirmative (default one), unanimous or consensus
        strategy: unanimous # if any voter returns ACCESS_DENIED, access is denied


回答3:

If i didn't get you wrong , i think hierarchical roles
is a better approach http://symfony.com/doc/current/book/security.html#hierarchical-roles) .

#Hierarchical Roles
Instead of associating many roles to users, you can define role inheritance rules by creating a role hierarchy:

YAML

app/config/security.yml
security:
    ...

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN:       ROLE_ADMIN
        ROLE_BOTH_ROLE_TOGETHER: [IS_AUTHENTICATED_FULLY,ROLE_ADMIN]

And them oyu can check for the hierarchy.