Symfony2 检查服务中的用户角色 [英] Symfony2 check user role in Service

查看:29
本文介绍了Symfony2 检查服务中的用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I check user role in code of a symfony2 Service? Should I simply send a user roles object to a Service or is there solution which allows me to do the check from Service level?

推荐答案

假设:

  • 你在你的服务中注入 security.context

public function __construct(SecurityContext $securityContext) {
  $this->securityContext = $securityContext;
}

  • 您正在使用 FosUserBundle

  • you are using FosUserBundle

    我正确理解你的问题:-)

    I understood correctly your question :-)

    你应该能够做到:

    $token = $this->securityContext->getToken();
    if (empty($token)) {
        return [];
    }
    $user = $token->getUser();
    if (empty($user)) {
        return [];
    }
    $roles = $user->getRoles();
    

    更新 2016/11/28

    1. 已更新答案以传递特定依赖项而不是整个容器,因为这是一种不好的做法(请参阅@Shady 的评论)
    2. 请注意,从 Symfony 2.6 开始,SecurityContext 已被弃用,您应该改用 TokenStorage.
    1. Answer updated to pass the specific dependency instead of the whole container, as that is a bad practice (see comment by @Shady)
    2. Note that starting from Symfony 2.6, SecurityContext is deprecated, you should use TokenStorage instead.

    这篇关于Symfony2 检查服务中的用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆