Symfony 2.8 -> 3.4 Upgrade IsGranted('IS_AUTHENTICATED_ANONYMOUSLY') Throws Errors

前端 未结 3 627
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 07:02

I\'m in the process of upgrading Symfony from 2.8 to 3.4 and I have a Authentication Listener.

The constructor of the listener

  public function __co         


        
相关标签:
3条回答
  • 2021-01-20 07:39

    Issue was with the priority order.

    thanks @cerad for giving a clue about it

    bin/console debug:event-dispatcher kernel.request
    

    helped to solve the issue. i was using

    tags:
            - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: 10 }
    

    in Services.yml and it had a conflict with the

    getSubscribedEvents()
    

    therefore i have removed tags and only kept

    public static function getSubscribedEvents()
        {
            return array(
                KernelEvents::REQUEST  => array('onKernelRequest', 10),
            );
        }
    

    then i moved authentication listener to the down by giving high priority to other two listeners as same as it was there in symfony 2.8

    Thanks all for helping me out on this specially @Pie @Cerad and @BoShurik

    0 讨论(0)
  • 2021-01-20 07:50

    Inject AuthorizationChecker to your class

    protected $authChecker;
    
    public function __construct(AuthorizationChecker $authChecker)
        {
            $this->authChecker = $authChecker;
        }
    

    By injecting it in your service.yml

    XXXXXXXXX:
        class: App\XXX\XXXX\XXXXX
        arguments: [ "@security.authorization_checker" ]
    

    And then use it to check role using isGranted

    if ($this->authChecker->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
    
    }
    
    0 讨论(0)
  • 2021-01-20 08:00

    I believe it's the securitycontext which has been deprecated / removed. isGranted needs to be called on the authorization checker

    return $this->get('security.authorization_checker');
    

    You need the 'security.authorization_checker' service.

    You then call isGranted on the authorization_checker service.

    // get the service from the container or pass it in via injection
    $authChecker = $this->get('security.authorization_checker');
    if ($authChecker->isGranted('IS...')) { ... }
    

    I used rector for easier migration. I would highly recommend https://github.com/rectorphp/rector for smooth migration. I can guarantee you will save lots of time by using this tool.

    https://www.tomasvotruba.cz/blog/2019/02/28/how-to-upgrade-symfony-2-8-to-3-4/

    0 讨论(0)
提交回复
热议问题