要在ApiPlatform的子资源路由上实现安全授权,可以使用Symfony的安全授权功能。以下是一个具体的解决方法,包含代码示例:
Book
实体类和一个Chapter
实体类,可以在Book
实体类中添加一个chapters
属性:use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ApiResource
* @ORM\Entity
*/
class Book
{
// ...
/**
* @ORM\OneToMany(targetEntity="Chapter", mappedBy="book")
*/
private $chapters;
public function __construct()
{
$this->chapters = new ArrayCollection();
}
public function getChapters(): Collection
{
return $this->chapters;
}
// ...
}
Chapter
实体类中添加一个book
属性:use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
/**
* @ApiResource
* @ORM\Entity
*/
class Chapter
{
// ...
/**
* @ORM\ManyToOne(targetEntity="Book", inversedBy="chapters")
* @ORM\JoinColumn(nullable=false)
*/
private $book;
public function getBook(): ?Book
{
return $this->book;
}
public function setBook(?Book $book): self
{
$this->book = $book;
return $this;
}
// ...
}
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
class SecureSubresourceDataProvider implements SubresourceDataProviderInterface, RestrictedDataProviderInterface
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
{
return true; // 支持所有子资源
}
public function getSubresource($data, array $identifiers, string $property, array $context = [])
{
// 检查授权
if (!$this->security->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException('Access denied.');
}
// 根据需要实现自定义的子资源逻辑
// 在这里,你可以查询数据库或调用其他服务来获取子资源数据。
// 返回子资源数据
return $data->{$property};
}
}
services.yaml
文件中注册自定义的数据提供器:services:
App\SecureSubresourceDataProvider:
arguments:
- '@security.authorization_checker'
api_platform.yaml
中指定使用自定义的数据提供器:api_platform:
mapping:
paths: ['%kernel.project_dir%/src/Entity']
collection:
data_provider: 'api_platform.collection_data_provider'
subresource:
data_provider: 'App\SecureSubresourceDataProvider'
以上就是在ApiPlatform的子资源路由上实现安全授权的解决方法,包含了相应的代码示例。请根据自己的需求进行相应的修改和调整。