AuthenticationSuccessHandlerInterface和正确的重定向策略

时间:2013-09-25 15:19:25

标签: symfony

我有一个登录success_handler,它将某些用户重定向到一个特殊的表单。 无论如何,AuthenticationSuccessHandlerInterface需要返回一个Response并且除了一个案例之外还能正常工作。如果用户首先填写他的凭证错误并再次重定向到登录页面,则处理程序会在正确登录后将其重定向到登录页面。

如果我只使用选项use_referer:true它可以正常工作。所以我可以把逻辑放到控制器而不是一个事件,但也许你们中的某个人有我的解决方案。

谢谢

防火墙

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            success_handler: applypie_userbundle.login.handler
            #default_target_path: applypie_user_dashboard
            use_referer: true
        logout:       true
        anonymous:    true

事件

namespace Applypie\Bundle\UserBundle\EventListener;

use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;


class NewUserListener implements AuthenticationSuccessHandlerInterface
{
    protected $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();

        if(!$user->getApplicant() && !count($user->getCompanies())) {

            return new RedirectResponse($this->router->generate('applypie_user_applicant_create'));

        }
            return new RedirectResponse($request->headers->get('referer'));
    }
}

服务

applypie_userbundle.login.handler:
    class: Applypie\Bundle\UserBundle\EventListener\NewUserListener
    arguments: ["@router"]

1 个答案:

答案 0 :(得分:6)

我很高兴看到你完成了重定向的东西。

您不需要use_referer,因为它将是登录页面URI(因为它是浏览器在标题中发送的真实引用),只需获取用户尝试从会话中访问的URI :

return new RedirectResponse($request->getSession()->get('_security.main.target_path'));

更多相关信息:

http://symfony.com/doc/current/cookbook/security/target_path.html

如果您处于开发模式(app_dev.php),您将找到许多重要信息,例如每个请求的会话值,请查看开发工具栏。