api-platform :自定义操作的安全性 [英] api-platform : how secure custom operation
问题描述
我想知道如何使用 api-platform 保护自定义 itemsOperation,我在文档中找到了此代码:
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
*/
但我想做类似的事情:
/**
* @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?
推荐答案
你应该考虑创建一个自定义的 symfony 选民
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;
}
}
然后您需要将您的选民定义为带有标签 security.voter
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 与选民类中定义的字符串相同
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 !
这篇关于api-platform :自定义操作的安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!