php ApiPlatform:子资源路由安全

q3aa0525  于 10个月前  发布在  PHP
关注(0)|答案(1)|浏览(67)

我正在把我的后端从APIPlate2.6升级到3.1。我有一个问题,配置安全的子资源,我没有找到任何有关的文件。
下面是一个子资源声明的示例:

#[ApiResource(
    uriTemplate: '/parent-entities/{id}/sub-entities.{_format}',
    operations: [new GetCollection()],
    uriVariables: [
        'id' => new Link(
            fromClass: SubEntityClass::class,
            toClass: ParentEntityClass::class,
            identifiers: ['parentEntity']
        ),
    ],
    security: 'is_granted(\'ROLE_USER\')'
)]

字符串
security当前安全注解工作正常,但我希望确保用户可以访问id为{id}的父实体资源。
我已经有了ParentEntity类的特定投票者。
现在,我想像这样添加安全性,但它不起作用:
第一个月
或者是
security: 'is_granted(\'ROLE_USER\') AND is_granted("VIEW", object)'
如果用户没有访问parentEntity资源的权限,我希望返回403。
有人有主意吗?
一个解决方案是不使用子资源而使用
1.在SubEntity中的parentEntity属性上添加API过滤器

#[ApiFilter(SearchFilter::class, properties: ['parentEntity.id' => 'exact'])]
    private ParentEntity $parentEntity;


1.网址:/sub-entities?parent-entity={id}
1.添加状态提供程序,并以编程方式检查安全性...

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $parentEntityIds = $context['filters']['parentEntity'] ?? [];
        
        // ...
            if (!$this->authorizationChecker->isGranted('VIEW', $parentEntity)) {
                throw new AccessDeniedException('Access Denied.');
            }
        // ...
    }


我有很多子资源,不想实现所有的东西…
谢谢大家
马努

jc3wubiy

jc3wubiy1#

据我所知,Api平台没有提供一种直接的方法来检查基于与标准投票者的manyToOne关系中的父实体的安全性。
但是,可以使用uriVariable作为voter中的主题。像这样定义你的ApiResource:

#[ApiResource(
    uriTemplate: '/parent_entities/{id}/children.{_format}',
    operations: [new GetCollection()],
    uriVariables: [
        'id' => new Link(
            toProperty: 'parent',
            fromClass: ParentEntity::class, identifiers: ['id']
        )
    ],
    security: 'is_granted("VIEW_BY_ID", id)'
)]

字符串
在你的voter中,你可以通过搜索你的父实体的“id”主题来检查它:

$parent = $this->em->getRepository(Company::class)->findOneBy(['id' => $subject]);
$user = $token->getUser();
return $user !== null && $parent->getOwner()->getId() === $user->getId();

相关问题