如何在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)
| 归档时间: |
|
| 查看次数: |
6498 次 |
| 最近记录: |