首页 > 解决方案 > 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', object)",
 *          "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并返回我想要的东西。

我阻止的部分是当我想向这条路线添加授权时:

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

但是当我运行我的测试时,我得到200了我应该收到403的地方,UserVoterorProductVoter没有被触发,也没有被触发is_granted('ROLE_ADMIN')

好像subresourceOperations注释没有被ApiPlatform.

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

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

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

这是一个已知问题ApiPlatform吗?

有谁看到我的逻辑在哪里失败?

是否有另一种方法来设置subresource路线的安全性?

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

标签: symfonysecurityapi-platform.comsubresource-integritysymfony4-voter

解决方案


推荐阅读