问题
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?
回答1:
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.
回答2:
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);
}
回答3:
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);
}
来源:https://stackoverflow.com/questions/29960224/symfony-2-adding-user-roles-under-the-role-user