Using Api-Platform, how to automatically add the authorized user as a resource owner when creating it?(使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?)
本文介绍了使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在创建时自动将当前授权用户添加到资源(POST
)。
我使用的是JWT身份验证,并且/api/routes受到保护,不会被未经授权的用户访问。我想对其进行设置,以便在经过身份验证的用户创建新资源(即通过向/api/articles
发送POST
请求)时,新创建的Article
资源与经过身份验证的用户相关。
我当前使用每个资源类型的自定义EventSubscriber
从令牌存储中添加用户。
及其扩展的实体订阅者: https://gist.github.com/dsuurlant/a8af7e6922679f45b818ec4ddad36286
但是,如果实体构造函数需要用户作为参数,则这不起作用。例如
class Book {
public User $owner;
public string $name;
public class __construct(User $user, string $name) {
$this->owner = $user;
$this->name = $name;
}
}
实体创建时如何自动注入授权用户?
推荐答案
我暂时使用DTOs and data transformers。
主要缺点是必须在需要此行为的地方为每个资源创建新的DTO。
作为一个简单的例子,我这样做:
class BootDtoTransformer implements DataTransformerInterface
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function transform($data, string $to, array $context = [])
{
$owner = $this->security->getUser();
return $new Book($owner, $data->name);;
}
public function supportsTransformation($data, string $to, array $context = []): bool
{
if ($data instanceof Book) {
return false;
}
return Book::class === $to && null !== ($context['input']['class'] ?? null);
}
}
这在逻辑上只对单个资源有效。为了拥有多个资源的泛型转换器,我最终使用了一些接口来区分"可拥有的"资源,并使用一些反射来实例化每个类。
我认为这在反规范化阶段是可行的,但我无法使其工作。
这篇关于使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Api-Platform,如何在创建时自动将授权用户添


基础教程推荐
猜你喜欢
- 将变量从树枝传递给 js 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- php中的foreach复选框POST 2021-01-01
- php中的PDF导出 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01