【问题标题】:TokenInterface $token->getUser() doesnt bring back an object令牌接口 $token->get User() 不带回对象
【发布时间】:2021-04-12 08:35:08
【问题描述】:

我正在使用 ApiPlatform 制作 CheeseListing RESTful API。

我为我的 CheeseListing 对象创建了一个投票者:

class CheeseListingVoter extends Voter
{

...

protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    // if the user is anonymous, do not grant access
    if (!$user instanceof UserInterface) {
    return false;
}

/** $var CheeseListing $subject */

// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
    case 'EDIT':
        if($subject->getOwner() === $user){
            return true;
        }
...

$token->getUser() 是一个对象而$subject->getOwner() 是一个Iri "/api/users/1" 时,为什么$subject->getOwner() === $user 会返回true

【问题讨论】:

  • 我要问一些愚蠢的问题:$subject->getOwner() 是一个 uri 听起来很意外,你确定吗?我的意思是,如果它确实是真的,那么人们会期望两者都是对象或两者都是 uri 或 bot 为空。呜呜……你怎么知道的?

标签: symfony entity api-platform.com symfony4-voter


【解决方案1】:

不要使用 if() 并尝试使用 id,因为在您的实体用户中,我认为您没有 getOwner()。 试试这个:

switch ($attribute) {
    case 'EDIT':
        return $subject->getId() === $user->getId()

【讨论】:

    【解决方案2】:

    答案:即使 ApiResource 的 /api/CheeseListing/ Get Endpoint 返回用户的 Iri : 喜欢

    {
        "title": "..."
        "owner": "/api/users/1"
    }
    

    Owner 字段实际上是一个对象。 ApiResource 有它自己的功能,可以将 Iri 转换为对象,反之亦然。

    在发布/api/CheeseListing 时同样适用,您会得到以下信息:

    {
        "title": "..."
        "owner": "/api/users/1"
    }
    

    它实际上是从"/api/users/1" 转换为用户对象

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2016-11-14
      • 2016-09-06
      • 2023-02-04
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2020-04-25
      • 2018-02-24
      相关资源
      最近更新 更多