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

谁说我不能喝 提交于 2019-12-20 02:23:25

问题


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 __construct(EntityManager $entityManager, SessionInterface $session, Security $security, LoggerInterface $logger, Redis $redis, $secret)
    {
        $this->entityManager    = $entityManager;
        $this->session          = $session;
        $this->security         = $security;
        $this->logger           = $logger;
        $this->redis            = $redis;
        $this->secret           = $secret;
    }

On Request Function which is calling in listener

       public function onRequest(GetResponseEvent $event)
        {

        //Validate token

        //Get Authorization Header
        $headers = $event->getRequest()->headers;
        $authHeader = $headers->get('Authorization');

        //Check if Header value starts with 'Bearer'
        if($this->startsWith($authHeader, self::$BEARER_HEADER)) {

                // Allow request to be processed by controllers
               //token handler


        } else {

            $securityContext = $this->security;
            if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
                return;
            } else {
                throw new SessionTimeoutException();
            }

        }
    }

Service.yml

app.token_listener:
    class: Insead\MIMBundle\Listener\AuthTokenListener
    arguments: ["@doctrine.orm.entity_manager", "@session", "@security.helper", "@logger", "@redis.authtoken", "%secret%"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onRequest, priority: 0 }

ACL list entry - security.php

  'access_control' => array(
       array('path' => '^/api/(.*?)/login', 'role'=>'IS_AUTHENTICATED_ANONYMOUSLY'),
    )

im trying to access login route with username and password but i get following error

GENERAL EXCEPTION: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. in

/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/AuthorizationChecker.php line 55 
Exception caught by Listener::  
[
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Security.php",
    "line": 65,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY",
      null
    ]
  },
  {
    "file": "/var/www/src/Insead/MIMBundle/Listener/AuthTokenListener.php",
    "line": 135,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Security",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY"
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 212,
    "function": "onRequest",
    "class": "Insead\\MIMBundle\\Listener\\AuthTokenListener",
    "type": "->",
    "args": [
      null,
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 44,
    "function": "doDispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      [
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ],
        [
          null,
          "onController"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "configure"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ]
      ],
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 127,
    "function": "dispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 68,
    "function": "handleRaw",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php",
    "line": 200,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1,
      true
    ]
  },
  {
    "file": "/var/www/web/app.php",
    "line": 29,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\Kernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      }
    ]
  }
]

I have spend days on this and i still couldn't figure it out to fix it.

Im sorry if this is already answered question i tried to search and i tried things which were mentioned in various posts and it didn't resolve it. im new to symfony too.

Full Security.php

https://www.codepile.net/pile/7O1LJkpv

AuthTokenListner.php

https://www.codepile.net/pile/Xv1ZMlAP


回答1:


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/




回答2:


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')) {

}



回答3:


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



来源:https://stackoverflow.com/questions/56338792/symfony-2-8-3-4-upgrade-isgrantedis-authenticated-anonymously-throws-erro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!