2016-12-07 50 views
0

我已经用Symfony2.8成功实现了FOSOAuthServerBundle并且工作正常。 当我尝试使用Symfony3.2工作时,出现错误:FOSOAuthServerBundle vs Symfony3安全指南

试图从命名空间“Symfony \ Component \ Security \ Core”加载类“SecurityContext”。 你忘记了另一个命名空间的“使用”语句吗?

所以我google了一下,现在知道SecurityContext在Symofny 3.2中不存在了。但是在FOSOAuthServerBundle官方文档中,“关于安全性的注意事项”仍然存在,函数loginAction()仅与symfony2兼容。

问题是: - 我可以在Symfony 3.2中使用这个包吗? - 如果是的话,是否有任何文件如何做到这一点,或更好的例子?

非常感谢你的答案

回答

1

不知道FOSOAuthServerBundle的细节。但我猜想a_note_about_security这个软件包的文档中的例子已经过时了。

自symfony 2.6开始,security.context服务已被弃用。在这里,你可以找到的变化说明:symfony.com/blog/new-in-symfony-2-6-security-component-improvements

你可以尝试用\Symfony\Component\Security\Core\Security

<?php 
// src/Acme/SecurityBundle/Controller/SecurityController.php 

namespace Acme\SecurityBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\Security\Core\Security; 

class SecurityController extends Controller 
{ 
    public function loginAction() 
    { 
     $request = $this->getRequest(); 
     $session = $request->getSession(); 

     // get the login error if there is one 
     if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) { 
      $error = $request->attributes->get(Security::AUTHENTICATION_ERROR); 
     } else { 
      $error = $session->get(Security::AUTHENTICATION_ERROR); 
      $session->remove(Security::AUTHENTICATION_ERROR); 
     } 

     // Add the following lines 
     if ($session->has('_security.target_path')) { 
      if (false !== strpos($session->get('_security.target_path'), $this->generateUrl('fos_oauth_server_authorize'))) { 
       $session->set('_fos_oauth_server.ensure_logout', true); 
      } 
     } 

     return $this->render('AcmeSecurityBundle:Security:login.html.twig', array(
      // last username entered by the user 
      'last_username' => $session->get(Security::LAST_USERNAME), 
      'error'   => $error, 
     )); 
    } 
} 
+0

是的,你是对的,只是不知道如何做到这一点。无论如何,非常感谢。 – milan74sa

0

更换\Symfony\Component\Security\Core\SecurityContext我想通了。 也许它有助于某人。

public function loginAction(Request $request) { 

    $authenticationUtils = $this->get('security.authentication_utils'); 

    $error = $authenticationUtils->getLastAuthenticationError(); 
    $lastUsername = $authenticationUtils->getLastUsername(); 

    return $this->render('AppBundle:Security:login.html.twig', array(
       'last_username' => $lastUsername 
       , 'error' => $error 
    )); 
}