symfony - 具有角色数组的 Twig is_granted()
问题描述
我试图将一个数组传递给 is_granted() 树枝过滤器但不起作用,尽管在文档中说是: https ://symfony.com/doc/current/reference/twig_reference.html#is-granted
想象一下 app.user 具有角色 ROLE_MANAGER。
例子:
{{ dump(is_granted('ROLE_MANAGER')) }}
这返回:真
{{ dump(is_granted(['ROLE_ADMIN','ROLE_MANAGER'])) }}
这返回:假
文件说:
角色:类型:字符串,字符串[]
如果当前用户具有给定角色,则返回 true。如果在一个数组中传递了多个角色,如果用户至少拥有其中一个,则返回 true。
但这不起作用......知道为什么吗?
解决方案
我遇到过同样的问题。我通过创建自定义选民解决了这个问题。出于某种原因,is_granted 函数不能像文档所说的那样工作。检查代码我注意到它从来没有为这个案例找到一个投票者,这就是我最终创建一个投票者的原因。
下面是我使用的选民示例:
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class MenuVoter extends Voter
{
/**
*
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject): bool
{
return $subject === null && \is_array($attribute);
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attributes, $post, TokenInterface $token): bool
{
$user = $token->getUser();
$r = false;
if (!($user instanceof UserInterface)) {
return false;
}
foreach ($attributes as $attribute) {
if ($this->security->isGranted($attribute)) {
$r = true;
break;
}
}
return $r;
}
}
它的基本作用是遍历每个角色(属性)并检查是否授予其中一个访问权限。
我希望它有所帮助,如果有人有更好的方法,我很想知道。
推荐阅读
- java - Spring Data MongoDB 通过 id 查询不返回结果
- groovy - JMeter:获取列标题列表及其索引
- c++ - C++ 在 Windows 中获取控制台应用程序以像在 linux 中一样快速打印
- hocon - 如何使用 hocon config 将对象定义为环境变量
- r - RStudio 自发地自我更新到更高版本
- solidity - 尝试编译代码时出现 Remix Solidity 错误
- python - 如何在 Django 中跨多个类运行测试装置?
- angularjs - 代码:“auth/argument-error”,消息:“reCAPTCHA 容器未找到或已包含内部元素!”,a:null Angular
- c# - Xamarin Forms - Android 应用程序在物理设备上崩溃
- android - 实现 FusedLocationProvider 时发生内存泄漏