2013-07-09 42 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% ]