RedirectionListener.php第46行中的FatalErrorException:错误:对非对象调用成员函数getUser()

RedirectionListener.php第46行中的FatalErrorException:错误:对非对象调用成员函数getUser(),php,symfony,fosuserbundle,Php,Symfony,Fosuserbundle,我对FOSUserBundle有问题 我有一个重定向侦听器,用于防止用户在未登录的情况下使用应用程序,代码如下: class RedirectionListener { /** * RedirectionListener constructor. * @param ContainerInterface $container * @throws \Symfony\Component\DependencyInjection\Exception\ServiceCircularRe

我对FOSUserBundle有问题

我有一个重定向侦听器,用于防止用户在未登录的情况下使用应用程序,代码如下:

class RedirectionListener
{
  /**
   * RedirectionListener constructor.
   * @param ContainerInterface $container
   * @throws \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
   * @throws \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
   */
   public function __construct(ContainerInterface $container)
   {
      $this->router = $container->get('router');
      $this->securityTokenStorage = $container->get('security.token_storage');
  }

  /**
   * @param GetResponseEvent $event
   * @throws \InvalidArgumentException
   */
   public function onKernelRequest(GetResponseEvent $event){

     $route = $event->getRequest()->attributes->get('_route');

     if($route !== 'fos_user_security_login' &&
        $route !== 'fos_user_resetting_reset' &&
        $route !== 'fos_user_resetting_request' &&
        $route !== 'fos_user_resetting_send_email' &&
        $route !== 'fos_user_resetting_check_email' &&
        $route !== 'fos_user_change_password' &&
        !is_object($this->securityTokenStorage->getToken()->getUser())) //this is line 46
      {
        $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
      }
  }
}
这是我的服务:

services:
redirectonListener:
    class: Projects\ProjectsBundle\Listener\RedirectionListener
    arguments: ['@service_container']
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
以下是我在FOSUserBundle文档中的防火墙设置:

firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
            # if you are using Symfony < 2.8, use the following config instead:
            # csrf_provider: form.csrf_provider

        logout:       true
        anonymous:    true
防火墙:
#禁用资产和探查器的身份验证,根据需要进行调整
开发人员:
模式:^/((探查器wdt)| css |图像| js)/
安全性:错误
主要内容:
模式:^/
表格(u)登入:
提供商:fos_用户包
csrf_令牌_生成器:security.csrf.token_管理器
#如果您使用的是Symfony<2.8,请改用以下配置:
#csrf\u提供程序:form.csrf\u提供程序
注销:正确
匿名:是的

我使用的是symfony2.8版本。有人能帮忙吗

您是否尝试在
security.yml
中设置
访问控制

例如:

security:
    #[...]

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # and so on, until:
        - { path: ^/restricted, role: ROLE_USER }
        # or:
        - { path: ^/*, role: IS_AUTHENTICATED_ANONYMOUSLY }


编辑:进行更改后,不要忘记清除缓存。

您是否尝试在
security.yml中设置
访问控制

例如:

security:
    #[...]

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # and so on, until:
        - { path: ^/restricted, role: ROLE_USER }
        # or:
        - { path: ^/*, role: IS_AUTHENTICATED_ANONYMOUSLY }


编辑:更改后不要忘记清除缓存。

我只是给您举个例子,以便您可以修改它以满足您的需要。除了监听器的操作方法外,您还应该研究FOS中的security.yml方法。有很多例子。例如,搜索
access\u control
,其中将提供6个示例供您学习

注意:切勿将整个容器作为服务参数注入

举几个例子

服务

services:
    application_frontend.event_listener.order_create:
        class: Application\FrontendBundle\EventListener\OrderCreateListener
        arguments:
            - @router
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
听众

namespace Application\FrontendBundle\EventListener;

use Application\FrontendBundle\Controller\OrderController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\RouterInterface;

class OrderCreateListener
{
    private $router;
    private $redirectRoute = 'fos_user_security_login';
    private $invalidRoutes = ['fos_user_security_login', '...', '...'];

    public function __construct(
        RouterInterface $router
    ) {
        $this->router = $router;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
        if (!is_array($controller)) {
            return;
        }

        if (
            $event->isMasterRequest() && // If it is user request
            $controller[0] instanceof OrderController && // Change it to your controller
            $this->isValidRoute($event) !== false
        ) {
            return;
        }

        $url = $this->router->generate($this->redirectRoute);
        $response = new RedirectResponse($url);
        $event->setResponse($response);
    }

    private function isCreateCarMethod(FilterControllerEvent $event)
    {
        $currentRoute = $event->getRequest()->attributes->get('_route');
        if (in_array(currentRoute, $this->invalidRoutes)) {
            return false;
        }
    }
}

我只是给你举个例子,这样你可以修改它来满足你的需要。除了监听器的操作方法外,您还应该研究FOS中的security.yml方法。有很多例子。例如,搜索
access\u control
,其中将提供6个示例供您学习

注意:切勿将整个容器作为服务参数注入

举几个例子

服务

services:
    application_frontend.event_listener.order_create:
        class: Application\FrontendBundle\EventListener\OrderCreateListener
        arguments:
            - @router
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
听众

namespace Application\FrontendBundle\EventListener;

use Application\FrontendBundle\Controller\OrderController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\RouterInterface;

class OrderCreateListener
{
    private $router;
    private $redirectRoute = 'fos_user_security_login';
    private $invalidRoutes = ['fos_user_security_login', '...', '...'];

    public function __construct(
        RouterInterface $router
    ) {
        $this->router = $router;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
        if (!is_array($controller)) {
            return;
        }

        if (
            $event->isMasterRequest() && // If it is user request
            $controller[0] instanceof OrderController && // Change it to your controller
            $this->isValidRoute($event) !== false
        ) {
            return;
        }

        $url = $this->router->generate($this->redirectRoute);
        $response = new RedirectResponse($url);
        $event->setResponse($response);
    }

    private function isCreateCarMethod(FilterControllerEvent $event)
    {
        $currentRoute = $event->getRequest()->attributes->get('_route');
        if (in_array(currentRoute, $this->invalidRoutes)) {
            return false;
        }
    }
}

在构造函数中:var_dump($container->get('security.token_storage');怎么说?我可能错了,但你不能这样检查吗?如果($this->get('security.authorization\u checker')->isgrated('IS\u AUTHENTICATED\u FULLY')==false)@Deep这是变量转储的结果:
object(Symfony\Component\security\Core\Authentication\Token\Storage\TokenStorage){264(1){[“Token”:“Symfony\Component\security\Core\Authentication\Token\Token\Storage\TokenStorage\TokenStorage”:private]=>NULL}
@ElSam next for try->getToken()和next and next。。但是我认为Thomas可能是正确的。@Thomas我有一个错误,它不工作
AuthenticationCredentialsNotFoundException in classes.php第2927行:令牌存储不包含认证令牌。一个可能的原因可能是没有为此URL配置防火墙。
在构造函数中:var_dump($container->get('security.token_storage');怎么说?我可能错了,但你不能这样检查吗?如果($this->get('security.authorization\u checker')->isgrated('IS\u AUTHENTICATED\u FULLY')==false)@Deep这是变量转储的结果:
object(Symfony\Component\security\Core\Authentication\Token\Storage\TokenStorage){264(1){[“Token”:“Symfony\Component\security\Core\Authentication\Token\Token\Storage\TokenStorage\TokenStorage”:private]=>NULL}
@ElSam next for try->getToken()和next and next。。但是我认为Thomas可能是正确的。@Thomas我有一个错误,它不工作
AuthenticationCredentialsNotFoundException in classes.php第2927行:令牌存储不包含认证令牌。一个可能的原因可能是没有为此URL配置防火墙。
非常感谢,我修改了我的security.yml文件如下:
访问控制:-{path:^/login$,role:is_AUTHENTICATED_匿名}-{path:^/register,role:is_AUTHENTICATED_匿名}-{path:^/restating,role:IS_AUTHENTICATED_ANONYMOUSLY}-{path:^/admin/,role:role_admin}-{path:^/*,role:role_USER}
它甚至不需要重定向侦听器就可以工作。非常感谢,我修改了security.yml文件如下:
访问控制:-{path:^/login$,role:IS_AUTHENTICATED_ANONYMOUSLY}-{path:^/register,role:IS_AUTHENTICATED_ANONYMOUSLY}-{path:^/login$,role:role_admin}-{path:^/*,role:role_USER}
它甚至不需要重定向侦听器就可以工作。感谢您的回答,我发现修改
security.yml
文件中的
access\u control
更合适。很好,您解决了它。正如我建议的那样,
access\u control
方法就是这样做的方法。感谢您的回答,我发现修改
access\c在
security.yml
文件中使用control
更合适。很好,您解决了它。正如我所建议的
access\u control
方法就是这样做的。