2013-07-09 66 views
6

我正在擴展身份驗證失敗處理程序,並且一切主要工作正常,但是有一個小問題。覆蓋身份驗證失敗處理程序 - Symfony2

這是我services.yml:

http.utils.class: 
    class: Symfony\Component\Security\Http\HttpUtils 
    auth.fail: 
    class: Acme\MyBundle\AuthenticationFailure 
    arguments: 
     - @http_kernel 
     - @http.utils.class 
     - [] 

我已將這security.yml使用:

failure_handler: auth.fail 

這是我的Acme \ MyBundle \ AuthenticationFailure.php:

namespace Acme\MyBundle; 

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Security\Core\Exception\AuthenticationException; 
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler; 
use Symfony\Component\HttpFoundation\Response; 

class AuthenticationFailure extends DefaultAuthenticationFailureHandler 
{ 

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) 
    { 

     //do something 

    } 

} 

問題是我在security.yml中設置的選項被忽略。我知道該類的_construct方法的第三個參數是$ options數組,並且我沒有傳入任何東西作爲第三個參數(在services.yml中),所以我猜這是問題,解決方案可能會是隻傳遞中的值我猜我也可以做這樣的事情:

arguments: 
    - @http_kernel 
    - @http.utils.class 
    - %security.firewalls.secure_area.form_login% 

....我沒有測試的問題是,這是硬編碼在services.yml它不是理想的,就好像我改變了它會破壞的secure_area的名字一樣。當然,這些價值可以更好地提供?

回答

8

我看到你試圖將login_path傳遞到您的身份驗證失敗處理程序...

...你應該注入@router,適應__construct方法和產生與路線名稱網址(不是模式),由防火牆在auth失敗處理程序中使用。然後重定向用戶那裏...

login_path: your_login_route_name # <- not a pattern like /login 

這樣改變防火牆的名稱不會破壞你的應用程序!


,如果你甚至不想破壞應用程序更改路線名稱可以讓這個配置藏漢時:

config.yml

parameters: 
    login.route_name: my_login_route_name 

的routing.yml

%login.route_name%: 
    pattern: /login 

security.yml

security: 
    firewalls: 
     your_firewall_name: 
      failure_handler: auth.fail 
      login_path:  %login.route_name% 

服務。陽明海運

auth.fail: 
    arguments: 
     - # ... 
     - @router 
     - %login.route_name% 

的Acme \ MyBundle \有authenticationFailure

use Symfony\Component\Routing\RouterInterface; 
use Symfony\Component\HttpFoundation\RedirectResponse; 

// ... 

protected $router; 

protected $loginRoute; 

public function __construct( 
    /** ... other arguments **/, 
    RouterInterface $router, 
    $loginRoute 
) 
{ 
    // .. 
    $this->router  = $router; 
    $this->loginRoute = $loginRoute; 
} 

public function onAuthenticationFailure(
    Request $request, 
    AuthenticationException $exception 
) 
{ 

    // ... 

    return new RedirectResponse($this->router->generate($this->loginRoute)); 
} 

關於你的建議,提示

(...使用類似%security.firewalls.secure_area.form_login%

您無法直接訪問安全配置(這些不是參數 - 您不能使用%security.firewall.whatever%! )...

的傳遞到__construct默認$options必須是一個數組...

...所以你可能需要通過[]包圍你傳遞的參數,如果這些參數不是一個數組。

arguments: 
    - [ %parameter1% , %parameter2% ]