简体   繁体   中英

Symfony 2 - Adding user roles under the ROLE_USER

I'm trying to create a new role in Symfony 2 below the default USER_ROLE (that role would have limited write access to some features). I am using FOSUserBundle.

I've written the following security settings so far but my ROLE_DEMO users still get the ROLE_USER.

role_hierarchy:
        ROLE_DEMO:        []
        ROLE_USER:        [ROLE_DEMO]
        ROLE_ADMIN:       [ROLE_USER, ROLE_SONATA_ADMIN]
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

Is it possible to create a role under the ROLE_USER in Symfony 2. If yes, how?

If you are using FOSUserBundle, it will give all users the ROLE_USER by default. ROLE_USER is present on every single hydrated user under the default FOSUserBundle setup (although not in the database). You could override that implementation by defining your own getRoles() method on your own User class. Or change the default role to ROLE_NONE (it doesn't really matter what). Or just avoid using ROLE_USER and come up with another role name for your actual users.

This is from the default User implementation

/* FOS\UserBundle\Model\User */
...
public function getRoles()
{
    $roles = $this->roles;

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }

    // we need to make sure to have at least one role
    $roles[] = static::ROLE_DEFAULT;

    return array_unique($roles);
}

A even shorter solution i came up with was to override the const ROLE_DEFAULT at the beginning of my owner User class.

class User extends BaseUser
{
    /** 
     * Override FOSUserBundle User base class default role.
     */
    const ROLE_DEFAULT = 'ROLE_DEMO';

    [...]
}

That way i did not even have to override the FOS user bundle getRoles() method.

for symfony 3 and 4

use this in you entity User

public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

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