Skip to content

Instantly share code, notes, and snippets.

@hansgrinwis
Last active November 20, 2020 20:46
Show Gist options
  • Save hansgrinwis/e023a8f865716537292567fe4ddf06be to your computer and use it in GitHub Desktop.
Save hansgrinwis/e023a8f865716537292567fe4ddf06be to your computer and use it in GitHub Desktop.
Symfony JSON logout (json_logout, logout via AJAX call)
<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Event\LogoutEvent;
/**
* Logout event subscriber.
*
* @author Hans Grinwis <[email protected]>
*/
final class LogoutSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [LogoutEvent::class => 'onLogout'];
}
public function onLogout(LogoutEvent $event): void
{
// json logout?
if (str_contains($event->getRequest()->getPreferredFormat(), 'json')) {
// 204 No Content
$event->setResponse(new Response(null, Response::HTTP_NO_CONTENT));
}
// else let logout continue with redirect
}
}
@hansgrinwis
Copy link
Author

hansgrinwis commented Nov 6, 2020

Please note that this invalidates the session, but it does not change local app state!

Also note that it seems to conflicts with explicitly setting security.firewalls.main.logout.target in Symfony 5.1. (See this.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment