I am trying to implement access control to the owner of an object. I am using the LexikJWTAuthenticationBundle, and access control works when I limit the check to roles, but it throws an exception when checking an object property.
I'm using API platform installed by composer on a Symfony 4.3 project. PHP is 7.2.19.
I can successfully limit the requests to logged in users by checking for roles, but when adding something like "object.owner == user" it fails with "hydra:description": "Cannot access private property App\Entity\Vehicle::$owner"
This is the entity class with the related fields.
/**
* @ApiResource(
* collectionOperations={"get"={"access_control"="is_granted('ROLE_USER')"}, "post"={"access_control"="is_granted('ROLE_USER')"}},
* itemOperations={"get"={"access_control"="is_granted('ROLE_USER') and object.owner == user"}, "put"={"access_control"="is_granted('ROLE_USER') and previous_object.owner == user"}},
* normalizationContext={"groups"={"vehicle:read"}},
* denormalizationContext={"groups"={"vehicle:write"}}
* )
* @ORM\Entity(repositoryClass="App\Repository\VehicleRepository")
* @ApiFilter(SearchFilter::class, properties={"owner": "exact"})
*/
class Vehicle
{
/**
* @Assert\NotBlank()
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="vehicles")
* @ORM\JoinColumn(nullable=false)
* @Groups({"vehicle:read", "vehicle:write"})
*/
private $owner;
public function getOwner(): User
{
return $this->owner;
}
}
This should have allowed only the owning user to get or update the vehicle, but it always fail with "hydra:description": "Cannot access private property App\Entity\Vehicle::$owner".
If I removed the "object.owner == user" annotation, but leave the check for ROLE_USER, then the operation is allowed.
is_granted()on any string like let's sayIS_OWNERand add a security voter that does the owner check - tsadiqobjectas second parameter ofis_granted()and it should be all good 👌 - tsadiqfunction getOwner(): ?User- Alexandre Tranchant