Overriding the authentication failure handler - Symfony2

前端 未结 1 1000
长情又很酷
长情又很酷 2021-02-04 19:19

I am extending the authentication failure handler and everything is mainly working ok, but for one small problem.

This is my services.yml:

  http.utils.c         


        
相关标签:
1条回答
  • 2021-02-04 19:52

    I see you're trying to pass the login_path to your authentication failure handler...

    ... you should inject @router, adapt the __construct method and generate the url with the route name ( not pattern ) used by your firewall inside the auth failure handler. then redirect the user there...

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

    this way changing the name of the firewall will not break your application!


    if you don't even want to break the application when changing the route name you can make this configurable aswell:

    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%
    

    services.yml

    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) ); 
    }
    

    Tip regarding your suggestion

    ( ... using something like %security.firewalls.secure_area.form_login% )

    you cannot access the security configuration directly ( these are not parameters - you can't use %security.firewall.whatever% ! ) ...

    The the default $options passed to __construct has to be an array ...

    ... so you might need to surround your passed parameters by [] if those parameters are not an array.

    arguments:
        - [ %parameter1% , %parameter2% ]
    
    0 讨论(0)
提交回复
热议问题