Pregunta

I have a basic form-login authentication in my app, and I set up a handler using AuthenticationHandlerInterface, in which I'm setting session vars in the onAuthenticationSuccess() method.

The problem is that when I switch to another user (using ROLE_ALLOWED_TO_SWITCH), my handler is not called anymore, and the session vars I set before remain those of the user before switching.

Example :

  • Logging with user X
  • Setting session var myVar to X->someAttribute (inside the authentication handler)
  • Switching to user Y
  • Handler not called : myVar keeps keeps the same value

(I know that myVar = X->someAttribute is not a good example since I can already access it from the security token object, but it was to simplify the problem)

Thanks

EDIT : extract of security.yml

firewalls:
    main:
        pattern:    ^/
        anonymous: ~
        switch_user: { role: ROLE_ADMIN, parameter: _switch }
        form_login:
            provider: sso
            success_handler: authentication_handler
            login_path: /login
            check_path: /login_check
        logout:
            path:   /logout
            target: /home
¿Fue útil?

Solución

When the security component success to switch the current user, it will dispatch an event security.switch_user with the following event class : https://github.com/symfony/symfony/blob/2.0/src/Symfony/Component/Security/Http/Event/SwitchUserEvent.php .

So you may need/want to listen to this event, and do your logic when your listener is called.

To listen to this event, read the symfony cookbook entry on listeners : http://symfony.com/doc/current/cookbook/service_container/event_listener.html

services:
    rocky.balboa.listener.security_switch_user:
        class: Rocky\BalboaBundle\Listener\SecuritySwitchUserListener
        tags:
            - { name: kernel.event_listener, event: security.switch_user, method: onSecuritySwitchUser }

.

// src/Rocky/BalboaBundle/Listener/SecuritySwitchUserListener.php

namespace Rocky\BalboaBundle\Listener;

use Symfony\Component\Security\Http\Event\SwitchUserEvent;

class SecuritySwitchUserListener
{
    public function onSecuritySwitchUser(SwitchUserEvent $event)
    {
        $newUser = $event->getTargetUser();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top