gpt4 book ai didi

Symfony2 检查服务中的用户角色

转载 作者:行者123 更新时间:2023-12-01 07:18:17 25 4
gpt4 key购买 nike

如何在 symfony2 服务的代码中检查用户角色?我应该简单地将用户角色对象发送到服务还是有允许我从服务级别进行检查的解决方案?

最佳答案

其他答案让您通过容器而不是授权检查器。当它们工作时,它们对容器产生了紧密的依赖,使得将代码迁移到其他项目变得更加困难。相反,您应该只通过授权检查器。

这是取自 symfony docs 的示例.

应用程序/配置/服务.yml

services:
newsletter_manager:
class: "AppBundle\Newsletter\NewsletterManager"
arguments: ["@security.authorization_checker"]

src/Appbundle/Newsletter/NewsletterManager.php
namespace AppBundle\Newsletter;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
// ...

class NewsletterManager
{
protected $authorizationChecker;

public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}

public function sendNewsletter()
{
if (false === $this->authorizationChecker->isGranted('ROLE_NEWSLETTER_ADMIN')) {
throw new AccessDeniedException();
}

// ...
}

// ...
}

关于Symfony2 检查服务中的用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com