Symfony 2 - 在 ROLE_USER 下添加用户角色
Symfony 2 - Adding user roles under the ROLE_USER
我正在尝试在 Symfony 2 中创建一个低于默认 USER_ROLE 的新角色(该角色对某些功能的写入权限有限)。我正在使用 FOSUserBundle。
到目前为止,我已经编写了以下安全设置,但我的 ROLE_DEMO 用户仍然获得 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]
是否可以在 Symfony 2 中的 ROLE_USER 下创建一个角色。如果是,如何?
如果您使用的是 FOSUserBundle,它会默认为所有用户提供 ROLE_USER
。 ROLE_USER
存在于默认 FOSUserBundle 设置下的每个 hydrated 用户中(尽管不在数据库中)。您可以通过在自己的 User
class 上定义自己的 getRoles()
方法来覆盖该实现。或者将默认角色更改为 ROLE_NONE
(这并不重要)。或者只是避免使用 ROLE_USER
并为您的实际用户想出另一个角色名称。
这是默认 User
实现
/* 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);
}
我想出的一个更短的解决方案是覆盖我所有者开头的 const ROLE_DEFAULT
User
class.
class User extends BaseUser
{
/**
* Override FOSUserBundle User base class default role.
*/
const ROLE_DEFAULT = 'ROLE_DEMO';
[...]
}
这样我什至不必覆盖 FOS 用户包 getRoles()
方法。
对于 symfony 3 和 4
在你的实体用户中使用这个
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
我正在尝试在 Symfony 2 中创建一个低于默认 USER_ROLE 的新角色(该角色对某些功能的写入权限有限)。我正在使用 FOSUserBundle。
到目前为止,我已经编写了以下安全设置,但我的 ROLE_DEMO 用户仍然获得 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]
是否可以在 Symfony 2 中的 ROLE_USER 下创建一个角色。如果是,如何?
如果您使用的是 FOSUserBundle,它会默认为所有用户提供 ROLE_USER
。 ROLE_USER
存在于默认 FOSUserBundle 设置下的每个 hydrated 用户中(尽管不在数据库中)。您可以通过在自己的 User
class 上定义自己的 getRoles()
方法来覆盖该实现。或者将默认角色更改为 ROLE_NONE
(这并不重要)。或者只是避免使用 ROLE_USER
并为您的实际用户想出另一个角色名称。
这是默认 User
实现
/* 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);
}
我想出的一个更短的解决方案是覆盖我所有者开头的 const ROLE_DEFAULT
User
class.
class User extends BaseUser
{
/**
* Override FOSUserBundle User base class default role.
*/
const ROLE_DEFAULT = 'ROLE_DEMO';
[...]
}
这样我什至不必覆盖 FOS 用户包 getRoles()
方法。
对于 symfony 3 和 4
在你的实体用户中使用这个
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}