lvarayut
lvarayut

Reputation: 15259

How to add a new role in Symfony2?

I am trying to configure a new role in Symfony2. I edited the security.yml file as following:

role_hierarchy:
        ROLE_Administrator:  [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        ROLE_Doctor: ROLE_ADMIN
        ROLE_Patient:  ROLE_USER
access_control:
        - { path: /login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_Administrator }

However, when I tried to login, I always got:

Access Denied 403 Forbidden - AccessDeniedHttpException 1 linked Exception: AccessDeniedException »

I read the document in the official Symfony2 site. I don't know what I did wrong.

Upvotes: 0

Views: 315

Answers (1)

Gianni Alessandro
Gianni Alessandro

Reputation: 910

In your security.yml, in your hierarchy and in your access control the roles must be the same.

role_hierarchy:
    ROLE_Administrator:  [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
    ROLE_Doctor: ROLE_ADMIN
    ROLE_Patient:  ROLE_USER
access_control:
    - { path: /login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: ROLE_ADMIN }

You define the ROLE that you need. You can call the admin as ROLE_ADMIN or ROLE_Administrator, as you want, but in every situation you have to use it with the same name. If you use two different name Symfony just think that you are referring to two different kind of role. Then, in your role_hierarchy, you can define that the ROLE_Doctor include the ROLE_ADMIN and so on... I haven't seen you controller, but surely you defined your user with a Role not allowed to see the path: ^/ because you passed the firewall (you are logged in) but not the access control (you are not allowed to see this page).

Attention because

    ROLE_Doctor: ROLE_ADMIN
    ROLE_Patient:  ROLE_USER

In the above configuration, users with ROLE_Doctor role will also have the ROLE_ADMIN role and ROLE_Patient will also have ROLE_USER role. Documentation here

Upvotes: 2

Related Questions