Symfony从4.1升级到4.4后调用authentication_utils报错如何解决?
问题原因
- Symfony 4.2+ 版本废弃了通过控制器
$this->get()方法直接从容器拉取服务的用法,4.4 版本默认关闭了普通控制器的容器访问权限,调用$this->get('security.authentication_utils')会直接抛出服务不存在的报错。
修复方案
推荐使用方法参数依赖注入的方式获取AuthenticationUtils服务,这是Symfony官方推荐的规范写法,适配4.4及后续所有版本:
- 首先在控制器顶部引入AuthenticationUtils类
- 将AuthenticationUtils作为参数注入loginAction方法
- 删除原有
$this->get()获取服务的代码
修改后完整代码如下:
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; public function loginAction (Request $request, AuthenticationUtils $authUtils) { // 获取登录过程中产生的错误(如果存在) $error = $authUtils->getLastAuthenticationError(); // 获取用户上次输入的用户名 $lastUsername = $authUtils->getLastUsername(); return $this->render('admin/user/login.html.twig', array( 'error' => $error, 'last_username' => $lastUsername, )); }
如果需要临时兼容旧代码不想做大规模修改,可以手动让你的控制器继承Symfony\Bundle\FrameworkBundle\Controller\AbstractController,即可恢复$this->get()方法的调用能力,但该方式属于兼容方案,不符合Symfony后续版本的开发规范,不建议长期使用。
内容的提问来源于stack exchange,提问作者mardon
相关产品推荐
相关产品推荐

