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

时间:2016-11-08 21:54:45

标签: php symfony fosuserbundle

我遇到了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

我正在使用Symfony 2.8版本。任何人都可以帮忙!

2 个答案:

答案 0 :(得分:2)

您是否尝试在access_control中设置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 }

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

答案 1 :(得分:0)

我只是给你一个例子,以便你可以修改它以满足你的需求。除了听众的方式,你应该在FOS中研究security.yml方法。有很多例子。例如,在http://www.inanzzz.com/中搜索access_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 }

<强> LISTENER

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;
        }
    }
}