smartius
smartius

Reputation: 653

AuthenticationSuccessHandlerInterface and correct redirect strategy

I have a login success_handler which redirects some users to a special form. Whatever, the AuthenticationSuccessHandlerInterface needs to return a Response and is working well except one case. if a user first fill in his credentials wrong and gets redirected to login page again, the handler redirects him AGAIN to login page after correct login.

if i simply use the option use_referer: true it works correct. So i could put the logic to the controller instead of an event but maybe someone of you guys has a solution for me.

thank you

firewall

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

event

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

service

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

Upvotes: 2

Views: 3465

Answers (1)

coma
coma

Reputation: 16659

I'm glad to see that you've accomplished the redirect stuff.

You don't need the use_referer since it'll be the login page URI (because it's the real referer sent by the browser in the headers), just take the URI the user tried to reach from the session:

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

more about this here:

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

If you are in dev mode (app_dev.php), you'll find a lot of great information, like session values for every request, take a look at the dev toolbar.

Upvotes: 8

Related Questions