Reputation: 80
I want to know how to secure custom itemsOperation with api-platform, I found this code on documentation:
/**
* Secured resource.
*
* @ApiResource(
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "get"={"method"="GET"},
* "post"={"method"="POST", "access_control"="is_granted('ROLE_ADMIN')"}
* },
* itemOperations={
* "get"{"method"="GET","access_control"="is_granted('ROLE_USER') and object.owner == user"}
* }
* )
* @ORM\Entity
*/
But I want to do something like:
/**
* @ApiResource(itemOperations={
* "get"={"method"="GET"} //Public route,
* "special"={"route_name"="special", "access_control"="is_granted('ROLE_ADMIN') or object.owner == user"}},
* "special2"={"route_name"="special2", "access_control"="is_granted('ROLE_USER')"}
* })
*/
Does it work? Or I have to check user roles in special Action file?
What is the best practice in this case?
Upvotes: 3
Views: 4253
Reputation: 1445
You should consider create a custom symfony voter
Please try this code, I'm here if you don't understand something with voters
<?php
namespace yournamespace;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class YourObjectVoter extends Voter
{
const YOUR_CUSTOM_ACTION = 'custom_action';
protected function supports($attribute, $subject)
{
if (!$subject instanceof YourObject) {
return false;
}
if (!in_array($attribute, array(self::YOUR_CUSTOM_ACTION))) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if($this->isGranted('ROLE_ADMIN')) {
return true;
}
$user = $token->getUser();
if(!$user instanceOf User) {
return false;
}
if($subject->getOwner() === $user) {
return true;
}
return false;
}
}
Then you need to define your voter as a service with the tag security.voter
class: Yournamespace\Security\YourObjectVoter
public: false
tags:
- { name: security.voter }
custom_action is the same string that the one defined in the voter class
With this code you can just secure your action with :
itemOperations={
* "get"{"method"="GET","access_control"="is_granted('custom_action', object)"}
* }
Let me know if It doesn't work. I hope it's help !
Upvotes: 6