6

当我在我的 symfony2 服务(树枝扩展)中注入 security.context 时,会出现以下错误:

在非对象上调用成员函数 getUser() .....

class GeninnoShareboardExtension extends \Twig_Extension {
    public function __construct(ContainerInterface $container, SecurityContext $context) {
        $this->doctrine = $container->get('doctrine');
        $this->context = $context;
    }

    public function getUser() {
        return $this->context->getToken()->getUser();
    }

    ........
}

我的 services.yml 看起来像这样:

services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments:
      container: "@service_container"
      service: "@security.context"
    tags:
     - { name: twig.extension }

用户已登录,我的防火墙设置如下:

access_control:
    - { path: ^/secured/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/create, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: [IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED] }
4

3 回答 3

2

你应该试试

services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments: [@service_container, @security.context]
    tags:
     - { name: twig.extension }
于 2013-04-05T15:02:11.130 回答
1

您收到错误的页面是否在防火墙后面?如果没有,那么它将无法访问安全令牌。您需要将页面置于防火墙后面,然后向未经身份验证的用户开放。

像这样的东西应该可以向未经身份验证的用户打开页面,但仍将其放在防火墙内(security.yml)

access_control:
  - { path: /lost_password, roles: IS_AUTHENTICATED_ANONYMOUSLY}
于 2013-04-05T16:19:36.403 回答
1

我通过在我的 SecurityContext 调用中添加一个 if 来解决它。检查 GetToken() 是否返回对象(已验证)或字符串(匿名)

if (is_object($this->context->getToken()))
{
    .... // getUser() etc.
}
于 2013-04-06T11:39:46.217 回答