问题描述
我正在使用 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()