Symfony2检查服务中的用户角色

Abd*_*el5 3 symfony

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

Yam*_*iko 12

其他答案是您传递容器而不是授权检查器.虽然它们工作,但它们对容器产生了严格的依赖性,使得将代码迁移到其他项目变得更加困难.相反,您应该只通过授权检查程序.

以下是从symfony文档中获取的示例.

应用程序/配置/ services.yml

services:
    newsletter_manager:
        class:     "AppBundle\Newsletter\NewsletterManager"
        arguments: ["@security.authorization_checker"]
Run Code Online (Sandbox Code Playgroud)

的src /的appbundle /新闻/ 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();
        }

        // ...
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • Imho这应该是接受的答案.将容器传递给服务被认为是不好的做法. (4认同)