不推荐使用Symfony 2 SecurityContext类

Har*_*joe 26 security symfony

当我尝试在symfony demo上访问app/example时出现以下错误

错误:自2.6版以来,不推荐使用Symfony\Component\Security\Core\SecurityContext类,并且将在3.0中删除它.请改用Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage或Symfony\Component\Security\Core\Authorization\AuthorizationChecker.

服务器正在以200状态代码返回正确的答案.

我在Google上没有发现任何关于它的信息.有没有人在遇到此错误之前和/或知道如何修复它?

flu*_*flu 47

说明

从Symfony 2.6开始,它 SecurityContext被拆分为TokenStorageAuthorizationChecker(参见:Symfony博客 - "Symfony 2.6中的新功能:安全组件改进").

这样做的主要原因是为了防止在注入SecurityContext您自己的服务时经常发生的循环引用.

更改本身是100%向后兼容(如链接的博客文章中所述),您只需要重写您访问的方式SecurityContext.

// Symfony 2.5
$user = $this->get('security.context')->getToken()->getUser();
// Symfony 2.6
$user = $this->get('security.token_storage')->getToken()->getUser();

// Symfony 2.5
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { ... }
// Symfony 2.6
if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { ... }
Run Code Online (Sandbox Code Playgroud)

你可以简单地尝试做一个文本搜索找到罪魁祸首security.context还是SecurityContext在源代码(包括供应商目录).

但正如你所说的那样,你使用的是vanilla Symfony 2.6,它似乎只是使用了一些很快被弃用的方法.所以你可能只是使用这个......

解决方法

由于Symfony通过触发E_USER_DEPRECATED错误来实现它的弃用,您可以在启动Symfony时禁用它们AppKernel:

// app/AppKernel.php
class AppKernel extends Kernel
{
    public function __construct($environment, $debug) {
        // Keep error reporting like it was and disable only deprecation warnings.
        error_reporting(error_reporting() & (-1 ^ E_DEPRECATED));
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我个人喜欢弃用警告,因为Symfony的更改日志倾向于提供有关如何更改代码以支持Symfony的未来版本的非常详细的信息,并且通常在方法实际弃用之前几个月触发弃用警告.