I have a working Symfony2 application that properly logs users in and out, and when logging out it properly redirects the user to the home page.
I'd like to keep them on their current page when the log out, only without their logged-in privileges.
My question is:
Can I dynamically set the page the user is directed to when they log out?
What you need is a logout success handler.
Define the logout handler in the security.yml:
security:
firewalls:
admin_area:
logout:
success_handler: acme.security.logout_success_handler
And the handler goes like this:
namespace Acme\Bundle\SecurityBundle\Handler;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerAware;
class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
{
public function onLogoutSuccess(Request $request)
{
// dynamic route logic
return new RedirectResponse($this->container->get('router')->generate('dynamic_route_name'));
}
}
Btw... Please remove the unwanted imports and Hope this helps! :D
Here is the services.yml
services:
acme.security.logout_success_handler:
class: Acme\Bundle\SecurityBundle\Handler\LogoutSuccessHandler
calls:
- [ setContainer, [ @service_container ] ]
I needed a Logout Success Handler, and this is how I implemented it:
security.yml:
logout:
success_handler: acme.security.logout_success_handler
config.yml:
services:
acme.security.logout_success_handler:
class: Acme\DefaultBundle\Handler\LogoutSuccessHandler
Symfony/src/Acme/DefaultBundle/Handler/LogoutSuccessHandler.php:
<?php
namespace Acme\DefaultBundle\Handler;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerAware;
class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
{
public function onLogoutSuccess(Request $request)
{
$target_url = $request->query->get('target_url')
? $request->query->get('target_url')
: "/";
return new RedirectResponse($target_url);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With