我正在使用Symfony5和ApiPlatform
我有一个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并返回我想要的东西。
我阻止的部分是当我想向这条路线添加授权时:
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了我应该收到403的地方,UserVoterorProductVoter没有被触发,也没有被触发is_granted('ROLE_ADMIN')。
好像subresourceOperations注释没有被ApiPlatform.
我还尝试将操作的名称从更改api_users_consultations_get_subresource为:
consultations_get_subresourceapi_consultations_get_subresourceclients_get_subresourceapi_clients_get_subresource
和我在上面看到的不同的其他变体Github在某些情况下解决了这个问题(比如这里https://github.com/api-platform/api-platform/issues/1581#issuecomment-662503549)但它对我不起作用。
所以我想知道我没有做些什么来正确实施它吗?
这是一个已知问题ApiPlatform吗?
有谁看到我的逻辑在哪里失败?
是否有另一种方法来设置subresource路线的安全性?
是否有更多关于安全性的文档subresource?我没有找到很多关于这个特定主题的材料