Last active
November 20, 2020 20:46
-
-
Save hansgrinwis/e023a8f865716537292567fe4ddf06be to your computer and use it in GitHub Desktop.
Symfony JSON logout (json_logout, logout via AJAX call)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)