Symfony2 检查服务中的用户角色

2024-01-12

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


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

这是一个取自以下示例symfony 文档 https://symfony.com/doc/current/security/securing_services.html.

应用程序/配置/services.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();
        }

        // ...
    }

    // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony2 检查服务中的用户角色 的相关文章

随机推荐