api-platform : how secure custom operation

两盒软妹~` 提交于 2019-12-06 06:25:19

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 !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!