首页 文章

AuthenticationSuccessHandler并在登录后重定向

提问于
浏览
1

我试图在我的symfony2应用程序登录后实现重定向,以便重定向,如果我的用户有一个属性 . 我在项目中的Handler文件夹中创建了AuthenticationSuccessHandler.php类:

namespace Me\MyBundle\Handler;

    use Symfony\Component\Security\Http\HttpUtils;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;


    class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler {

        public function __construct( HttpUtils $httpUtils, array $options ) {
            parent::__construct( $httpUtils, $options );
        }

        public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {


        $user = $token->getUser();

        if($user->getProfile()!=1){
            $url = 'fos_user_profile_edit';
        }else{
            $url = 'My_route';
        }

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

但是当我登录时,我收到一个错误:

注意:未定义的属性:Me / MyBundle \ Handler \ AuthenticationSuccessHandler :: $ router in /var/www/MyBundle/src/Me/MyBundle/Handler/AuthenticationSuccessHandler.php第28行

The error is in happening in the "return new RedirectResponse($this->router->generate($url));"

我也有我的服务:

my_auth_success_handler:
            class: Me\MyBundle\Handler\AuthenticationSuccessHandler
            public: false
            arguments: [ @security.http_utils, [] ]

和security.yml中的成功处理程序:

fos_facebook:
            success_handler: my_auth_success_handler

有任何想法吗?非常感谢你 .

2 回答

  • 3

    您没有注入 @router 服务 . 修改你的构造函数

    protected $router;
    public function __construct( HttpUtils $httpUtils, array $options, $router ) {
        $this->router = $router;
        parent::__construct( $httpUtils, $options );
    }
    

    和服务定义:

    ...
    arguments: [ @security.http_utils, [], @router ]
    
  • 0

    使用Symfony> = 2.8,您可以使用AutowirePass简化服务定义 .

    use Symfony\Component\Routing\Router; 
    use Symfony\Component\Security\Http\HttpUtils;
    
    class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler 
    {
    
        /**
         * @var Router
         */
        protected $router;
    
        public function __construct(HttpUtils $httpUtils, array $options = [], Router $router) 
        {
            parent::__construct($httpUtils, $options);
            $this->router = $router;
        }
    

    请注意,默认值“$ options = []”对于AutowirePass很重要:如果没有,则抛出异常 . 但是你有一个空数组 .

    到services.yml:

    my_auth_success_handler:
            class: Me\MyBundle\Handler\AuthenticationSuccessHandler
            public: false
            autowire: true
    

    这里不需要指定参数;-)

相关问题