AuthenticationSuccessHandlerInterface和正确的重定向策略

sma*_*ius 1 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
Run Code Online (Sandbox Code Playgroud)

事件

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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

服务

applypie_userbundle.login.handler:
    class: Applypie\Bundle\UserBundle\EventListener\NewUserListener
    arguments: ["@router"]
Run Code Online (Sandbox Code Playgroud)

com*_*oma 6

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

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

return new RedirectResponse($request->getSession()->get('_security.main.target_path'));
Run Code Online (Sandbox Code Playgroud)

更多相关信息:

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

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