微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ApiPlatform - 在子资源路由上实现安全授权

如何解决ApiPlatform - 在子资源路由上实现安全授权

我正在使用 Symfony5ApiPlatform

我有一个 User 实体和一个 Product 实体。

我想通过子资源列出我所有用户的产品,为此我实现了我的 user 类,如下所示:


/**
 * @ApiResource(
 *     attributes={
 *          "normalization_context"={"groups"={"user:read","user:list"}},*          "denormalization_context"={"groups"={"user:put","user:post"}}
 *     },*    subresourceOperations={
 *         "api_users_consultations_get_subresource"={
 *             "method"="GET",*             "security"="is_granted('ROLE_ADMIN')"
 *         }
 *    },*    collectionoperations={
 *        "get"={
 *              "method"="GET",*              "security"="is_granted('ROLE_ADMIN')",*              "normalization_context"={"groups"={"user:list"}}
 *          },*        "post"={
 *              "method"="POST",*              "security_post_denormalize"="is_granted('POST',object)",*              "denormalization_context"={"groups"={"user:post"}}
 *        }
 *    },*    itemOperations={
 *        "get"={
 *          "method"="GET",*          "security"="is_granted('GET',*          "normalization_context"={"groups"={"user:read"}}
 *         }
 *    }
 * )
 * @Gedmo\SoftDeleteable(fieldName="deletedAt",timeAware=false,hardDelete=false)
 * @ORM\Entity(repositoryClass=UserRepository::class)
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups({"user:read","user:list"})
     *
     */
    private $id;

    /**
     * @ORM\OnetoMany(targetEntity=Product::class,mappedBy="user")
     * @ApiSubresource()
     */
    private $product;
}

它确实创建了一条路线 /users/{id}/products 并返回我想要的东西。

我阻止的部分是当我想为此路由添加授权时:

  • ROLE_ADMIN 可以访问此路线
  • ROLE_USER 拥有资源的人可以访问它
  • 所有其他角色都将收到 FORBIDDEN

为此,我遵循了文档:https://api-platform.com/docs/core/subresources/#using-serialization-groups

  • subresourceOperations 注释中添加@ApiSubresource
  • 通过 api_users_consultations_get_subresource 命令恢复了我的绿色路线 bin/console debug:router名称
  • 并像其他操作一样简单地设置一个 security=is_granted('ROLE_ADMIN') 方法
  • security=is_granted('SUB_LIST',object)点击Voter

但是当我运行我的测试时,我得到了 200,我应该收到 403UserVoterProductVoter 没有触发,也没有触发 is_granted('ROLE_ADMIN') 规则。

好像 subresourceOperations 无法识别 ApiPlatform 注释一样。

我还尝试将操作名称api_users_consultations_get_subresource 更改为 :

  • consultations_get_subresource
  • api_consultations_get_subresource
  • clients_get_subresource
  • api_clients_get_subresource

以及我在 Github 上看到的其他不同变体,它在某些情况下解决了该问题(例如 https://github.com/api-platform/api-platform/issues/1581#issuecomment-662503549),但对我不起作用。

所以我想知道是不是我没有做些什么来正确实施它?

这是 ApiPlatform 的已知问题吗?

有人看到我的逻辑在哪里失败了吗?

还有其他方法可以在 subresource 路由上设置安全性吗?

是否有更多关于 subresource 的安全文档?我没有找到很多关于这个特定主题的材料

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。