如何解决TokenInterface $token->getUser() 不带回一个对象
我正在使用 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;
}
...
当 $subject->getOwner() === $user
是一个对象而 $token->getUser()
是一个 Iri "/api/users/1" 时,为什么 $subject->getOwner()
会返回 true
解决方法
答案:即使 ApiResource 的 /api/CheeseListing/
Get Endpoint 返回用户的 Iri :
喜欢
{
"title": "..."
"owner": "/api/users/1"
}
Owner 字段实际上是一个对象。 ApiResource 有它自己的功能,可以将 Iri 转换为对象,反之亦然。
发布/api/CheeseListing
时同样适用,您会得到以下内容:
{
"title": "..."
"owner": "/api/users/1"
}
它实际上是从 "/api/users/1"
转换为 User 对象
不要使用 if() 并尝试使用 id,因为在您的实体用户中,我认为您没有 getOwner()。 试试这个:
switch ($attribute) {
case 'EDIT':
return $subject->getId() === $user->getId()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。