2016-12-07 46 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 
    )); 
}