Symfony 2.8 -> 3.4 升级 IsGranted('IS_AUTHENTICATED_ANONYMOUSLY') 抛出错误

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

我正在将 Symfony 从 2.8 升级到 3.4,并且我有一个身份验证侦听器。

监听器的构造函数

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

在侦听器中调用的请求函数

       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 列表条目 - security.php

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

我正在尝试使用用户名和密码访问登录路径,但出现以下错误

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

我已经花了好几天时间解决这个问题,但我仍然无法解决它。

如果这个问题已经得到解答,我很抱歉,我尝试搜索并尝试了各种帖子中提到的问题,但没有解决。我也是 symfony 的新手。

完整 Security.php

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

AuthTokenListner.php

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

我相信这是已弃用/删除的安全上下文。需要在授权检查器上调用 isGranted

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

您需要 'security.authorization_checker' 服务。

然后您在 authorization_checker 服务上调用 isGranted。

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

为了更容易迁移,我使用了 rector。我强烈推荐 https://github.com/rectorphp/rector 以便顺利迁移。我可以保证您使用这个工具会节省很多时间。

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

AuthorizationChecker 注入到您的 class

protected $authChecker;

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

将其注入您的 service.yml

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

然后使用它来检查角色使用 isGranted

if ($this->authChecker->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {

}

问题与优先顺序有关。

感谢@cerad 提供线索

bin/console debug:event-dispatcher kernel.request

帮助解决了问题。我正在使用

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

在 Services.yml 中,它与

有冲突
getSubscribedEvents()

因此我删除了标签,只保留了

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

然后我通过给予其他两个侦听器高优先级将身份验证侦听器向下移动,就像在 symfony 2.8 中一样

特别感谢大家帮我解决这个问题@Pie @Cerad 和@BoShurik